我正在连接到 Exchange 服务器以进行远程 powershell 会话,下面有一个代码示例。
我不想硬编码“exchangeServerName”变量,以防该框脱机,我无法运行
Get-ExchangeServer | Where-Object {$_.IsMailboxServer -Eq $true -and $_.AdminDisplayVersion -Match "^Version 15" } | Select Name
因为我需要硬编码一个服务器名称才能运行该命令。关于执行此操作的最佳方法的任何建议?我不想硬编码任何东西。
谢谢!
string un = @"domain\username";
System.Security.SecureString pw = new System.Security.SecureString();
string password = "password";
string databaseName = "databasename";
string exchangeServerName = "http://exchangeserver.com/powershell";
string microsoftSchemaName = "http://schemas.microsoft.com/powershell/Microsoft.Exchange";
foreach (char ch in password)
{
pw.AppendChar(ch);
}
PSCredential cred = new PSCredential(un, pw);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(exchangeServerName), microsoftSchemaName, cred);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
using (PowerShell powershell = PowerShell.Create())
{
powershell.AddCommand("Get-Mailboxdatabasecopystatus");
powershell.AddParameter("identity", databaseName);
powershell.AddCommand("select-object");
var props = new string[] { "name", "status" };
powershell.AddParameter("property", props);
runspace.Open();
powershell.Runspace = runspace;
Collection<PSObject> results = powershell.Invoke();
foreach (PSObject result in results)
{
MessageBox.Show(result.ToString());
}
}
}