我.NET開發人員,有一次,我的任務,使MVC UI與Microsoft Exchange服務器進行交互和管理郵箱AD用戶,我不得不學習PowerShell和如何通過C#PowerShell的互動。所以根據我的經驗,我會建議你開始學習C#使用控制檯應用程序,瞭解c#如何與Powershell和AD協同工作,並開始學習MVC構建UI。
你應該從NuGet包管理器安裝包System.management.Automation。
C#=> Powershell(執行Powershell命令)=> Microsoft Exchange。
簡單示例,獲取用戶PrimarySmtpAddress屬性。
using System.Management.Automation;
using System.Management.Automation.Runspaces;
private static WSManConnectionInfo _connectionInfo;
static void Main(string[] args)
{
string userName = "DOMAIN\\User";
string password = "UserPassowrd";
PSCredential psCredential = new PSCredential(userName, GenerateSecureString(password));
_connectionInfo = new WSManConnectionInfo(
new Uri("http://server.domain.local/PowerShell"),
"http://schemas.microsoft.com/powershell/Microsoft.Exchange", psCredential);
_connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
Console.WriteLine(GetPrimarySmtpAddressBy("Firstname Lastname");
}
public static string GetPrimarySmtpAddressBy(string identity)
{
using (Runspace runspace = RunspaceFactory.CreateRunspace(_connectionInfo))
{
using (PowerShell powerShell = PowerShell.Create())
{
powerShell.AddCommand("Get-Mailbox");
powerShell.AddParameter("Identity", identity);
runspace.Open();
powerShell.Runspace = runspace;
PSObject psObject = powerShell.Invoke().FirstOrDefault();
if (psObject != null && psObject.Properties["PrimarySmtpAddress"] != null)
return psObject.Properties["PrimarySmtpAddress"].Value.ToString();
else return "";
}
}
}
public static System.Security.SecureString GenerateSecureString(string input)
{
System.Security.SecureString securePassword = new System.Security.SecureString();
foreach (char c in input)
securePassword.AppendChar(c);
securePassword.MakeReadOnly();
return securePassword;
}
感謝您的洞察,謝謝! – JustAGuy