在 C# 中连接到 Microsoft Exchange PowerShell
Connect to Microsoft Exchange PowerShell within C#
我正在尝试从 C# .NET WinForms 应用程序连接到远程 powershell。我的目标是创建我自己的 Microsoft PowerShell ISE 版本。所以我需要一种方法来从我的应用程序在远程机器上执行 PowerShell 脚本。我已经创建了几种方法并通过我的应用程序在本地机器上对其进行了测试。如果我不使用 WSManConnectionInfo 并使用 using (Runspace remoteRunspace = RunspaceFactory.CreateRunspace()) 我可以在本地执行脚本,就像它一样是真正的 powershell(小脚本、变量的使用、使用 ft、fl 的输出数据,做很多我通常用 powershell 做的其他事情。当我添加 WSManConnectionInfo 并将其指向我的 Exchange Server 而不是使用本地连接时,问题就开始了。它似乎能够执行基本的东西,比如“get-mailbox”,但是当我尝试管东西,使用一些脚本功能,如 $variables 它打破说它不受支持。
同样,当我不在本地使用它时,我必须禁用 powershell.AddCommand("out-string");。
An unhandled exception of type 'System.Management.Automation.RemoteException' occurred in System.Management.Automation.dll.
Additional information: The term 'Out-String' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
如果我不强制远程连接而只是在本地连接,则不会出现完全相同的错误。似乎 SchemaUri 使得只执行基本命令变得非常严格。我看到其他示例,其中人们使用非常直接的信息,例如我们:
powershell.AddCommand("Get-Users");
powershell.AddParameter("ResultSize", count);
但是使用这种方法我将不得不定义很多可能的选项并且我不想通过定义参数和其他东西来完成。我只是想加载“脚本”并像在 PowerShell window 中一样执行它。这是我现在使用的示例。
public static WSManConnectionInfo PowerShellConnectionInformation(string serverUrl, PSCredential psCredentials)
{
var connectionInfo = new WSManConnectionInfo(new Uri(serverUrl), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", psCredentials);
//var connectionInfo = new WSManConnectionInfo(new Uri(serverUrl), "http://schemas.microsoft.com/powershell", psCredentials);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
connectionInfo.SkipCACheck = true;
connectionInfo.SkipCNCheck = true;
connectionInfo.SkipRevocationCheck = true;
connectionInfo.MaximumConnectionRedirectionCount = 5;
connectionInfo.OperationTimeout = 150000;
return connectionInfo;
}
public static PSCredential SecurePassword(string login, string password)
{
SecureString ssLoginPassword = new SecureString();
foreach (char x in password) { ssLoginPassword.AppendChar(x); }
return new PSCredential(login, ssLoginPassword);
}
public static string RunScriptPs(WSManConnectionInfo connectionInfo, string scriptText)
{
StringBuilder stringBuilder = new StringBuilder();
// Create a remote runspace using the connection information.
//using (Runspace remoteRunspace = RunspaceFactory.CreateRunspace())
using (Runspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
// Establish the connection by calling the Open() method to open the runspace.
// The OpenTimeout value set previously will be applied while establishing
// the connection. Establishing a remote connection involves sending and
// receiving some data, so the OperationTimeout will also play a role in this process.
remoteRunspace.Open();
// Create a PowerShell object to run commands in the remote runspace.
using (PowerShell powershell = PowerShell.Create())
{
powershell.Runspace = remoteRunspace;
powershell.AddScript(scriptText);
//powershell.AddCommand("out-string");
powershell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
Collection<PSObject> results = powershell.Invoke();
foreach (PSObject result in results) {
stringBuilder.AppendLine(result.ToString());
}
}
// Close the connection. Call the Close() method to close the remote
// runspace. The Dispose() method (called by using primitive) will call
// the Close() method if it is not already called.
remoteRunspace.Close();
}
// convert the script result into a single string
return stringBuilder.ToString();
}
关于为什么会发生这种情况的任何建议以及如何使其以相同方式运行的解决方法?我看过很多像 this but defining every simple command doesn't make sense to me. I also saw an option to create local connection and then execute remote connection within that 这样的博客,但这是最后的选择,因为它依赖于其他多个因素。
您的 运行 似乎遇到了双跳身份验证问题,我在尝试此问题时遇到了同样的问题。
经过一番折腾,我最终在本地安装了 Exchange Powershell 插件,并使用它们远程连接到 Exchange 服务器。
粗略示例:
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
PSSnapInInfo info = runspaceConfiguration.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapInException);
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
using (PowerShell powershell = PowerShell.Create())
{
powershell.Runspace = runspace;
string script = string.Format(@"Get-Mailbox -Server {0} -Identity {1}", serverName, identity);
powershell.AddScript(script);
powershell.Invoke();
// Do something with the output
}
The management experience given by Exchange 2010 through PowerShell
has been moved all the way from Local to Remote. [...] Only exchange cmdlets will work in this remoting scenario, you will not be able to run most of the powershell cmdlets. [...] Yes, this does mean that you will not be able to run cmdlets like Where-Object and .PS1 scripts in the Remote Runspace.
Is that a limitation? I don’t think so. We can very easily get around it by create a new Session and Importing it.
所以你需要像这样:
PSCredential creds = new PSCredential(userName, securePassword);
System.Uri uri = new Uri("http://Exchange-Server/powershell?serializationLevel=Full");
Runspace runspace = RunspaceFactory.CreateRunspace();
PowerShell powershell = PowerShell.Create();
PSCommand command = new PSCommand();
command.AddCommand("New-PSSession");
command.AddParameter("ConfigurationName", "Microsoft.Exchange");
command.AddParameter("ConnectionUri", uri);
command.AddParameter("Credential", creds);
command.AddParameter("Authentication", "Default");
powershell.Commands = command;
runspace.Open(); powershell.Runspace = runspace;
Collection<PSSession> result = powershell.Invoke<PSSession>();
powershell = PowerShell.Create();
command = new PSCommand();
command.AddCommand("Set-Variable");
command.AddParameter("Name", "ra");
command.AddParameter("Value", result[0]);
powershell.Commands = command;
powershell.Runspace = runspace;
powershell.Invoke();
powershell = PowerShell.Create();
command = new PSCommand();
command.AddScript("Import-PSSession -Session $ra");
powershell.Commands = command;
powershell.Runspace = runspace;
powershell.Invoke();
# now you can use remote PS like it's local one
从 Exchange Server 2010 开始,您需要使用远程 PowerShell 会话,而不是直接添加 exchange PowerShell 管理单元(由于在 exchange 2010 中使用 RBAC 而不是 ACL)。
因此,您需要创建新的 PowerShell 会话(使用 New-PSSession),然后导入它(使用 Import-PSSession)。
您可以使用这样的代码远程执行 PowerShell 命令:
void ExecutePowerShellUsingRemotimg()
{
RunspaceConfiguration runspaceConfig = RunspaceConfiguration.Create();
PSSnapInException snapInException = null;
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfig);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
string serverFqdn = "FQDN of you server";
pipeline.Commands.AddScript(string.Format("$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://{0}/PowerShell/ -Authentication Kerberos", serverFqdn));
pipeline.Commands.AddScript("Import-PSSession $Session");
pipeline.Commands.AddScript("your PowerShell script text");
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
StringBuilder sb = new StringBuilder();
if (pipeline.Error != null && pipeline.Error.Count > 0)
{
// Read errors
succeeded = false;
Collection<object> errors = pipeline.Error.ReadToEnd();
foreach (object error in errors)
sb.Append(error.ToString());
}
else
{
// Read output
foreach (PSObject obj in results)
sb.Append(obj.ToString());
}
runspace.Dispose();
pipeline.Dispose();
}
我正在尝试从 C# .NET WinForms 应用程序连接到远程 powershell。我的目标是创建我自己的 Microsoft PowerShell ISE 版本。所以我需要一种方法来从我的应用程序在远程机器上执行 PowerShell 脚本。我已经创建了几种方法并通过我的应用程序在本地机器上对其进行了测试。如果我不使用 WSManConnectionInfo 并使用 using (Runspace remoteRunspace = RunspaceFactory.CreateRunspace()) 我可以在本地执行脚本,就像它一样是真正的 powershell(小脚本、变量的使用、使用 ft、fl 的输出数据,做很多我通常用 powershell 做的其他事情。当我添加 WSManConnectionInfo 并将其指向我的 Exchange Server 而不是使用本地连接时,问题就开始了。它似乎能够执行基本的东西,比如“get-mailbox”,但是当我尝试管东西,使用一些脚本功能,如 $variables 它打破说它不受支持。
同样,当我不在本地使用它时,我必须禁用 powershell.AddCommand("out-string");。
An unhandled exception of type 'System.Management.Automation.RemoteException' occurred in System.Management.Automation.dll.
Additional information: The term 'Out-String' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
如果我不强制远程连接而只是在本地连接,则不会出现完全相同的错误。似乎 SchemaUri 使得只执行基本命令变得非常严格。我看到其他示例,其中人们使用非常直接的信息,例如我们:
powershell.AddCommand("Get-Users");
powershell.AddParameter("ResultSize", count);
但是使用这种方法我将不得不定义很多可能的选项并且我不想通过定义参数和其他东西来完成。我只是想加载“脚本”并像在 PowerShell window 中一样执行它。这是我现在使用的示例。
public static WSManConnectionInfo PowerShellConnectionInformation(string serverUrl, PSCredential psCredentials)
{
var connectionInfo = new WSManConnectionInfo(new Uri(serverUrl), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", psCredentials);
//var connectionInfo = new WSManConnectionInfo(new Uri(serverUrl), "http://schemas.microsoft.com/powershell", psCredentials);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
connectionInfo.SkipCACheck = true;
connectionInfo.SkipCNCheck = true;
connectionInfo.SkipRevocationCheck = true;
connectionInfo.MaximumConnectionRedirectionCount = 5;
connectionInfo.OperationTimeout = 150000;
return connectionInfo;
}
public static PSCredential SecurePassword(string login, string password)
{
SecureString ssLoginPassword = new SecureString();
foreach (char x in password) { ssLoginPassword.AppendChar(x); }
return new PSCredential(login, ssLoginPassword);
}
public static string RunScriptPs(WSManConnectionInfo connectionInfo, string scriptText)
{
StringBuilder stringBuilder = new StringBuilder();
// Create a remote runspace using the connection information.
//using (Runspace remoteRunspace = RunspaceFactory.CreateRunspace())
using (Runspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
// Establish the connection by calling the Open() method to open the runspace.
// The OpenTimeout value set previously will be applied while establishing
// the connection. Establishing a remote connection involves sending and
// receiving some data, so the OperationTimeout will also play a role in this process.
remoteRunspace.Open();
// Create a PowerShell object to run commands in the remote runspace.
using (PowerShell powershell = PowerShell.Create())
{
powershell.Runspace = remoteRunspace;
powershell.AddScript(scriptText);
//powershell.AddCommand("out-string");
powershell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
Collection<PSObject> results = powershell.Invoke();
foreach (PSObject result in results) {
stringBuilder.AppendLine(result.ToString());
}
}
// Close the connection. Call the Close() method to close the remote
// runspace. The Dispose() method (called by using primitive) will call
// the Close() method if it is not already called.
remoteRunspace.Close();
}
// convert the script result into a single string
return stringBuilder.ToString();
}
关于为什么会发生这种情况的任何建议以及如何使其以相同方式运行的解决方法?我看过很多像 this but defining every simple command doesn't make sense to me. I also saw an option to create local connection and then execute remote connection within that 这样的博客,但这是最后的选择,因为它依赖于其他多个因素。
您的 运行 似乎遇到了双跳身份验证问题,我在尝试此问题时遇到了同样的问题。
经过一番折腾,我最终在本地安装了 Exchange Powershell 插件,并使用它们远程连接到 Exchange 服务器。
粗略示例:
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
PSSnapInInfo info = runspaceConfiguration.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapInException);
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
using (PowerShell powershell = PowerShell.Create())
{
powershell.Runspace = runspace;
string script = string.Format(@"Get-Mailbox -Server {0} -Identity {1}", serverName, identity);
powershell.AddScript(script);
powershell.Invoke();
// Do something with the output
}
The management experience given by Exchange 2010 through PowerShell has been moved all the way from Local to Remote. [...] Only exchange cmdlets will work in this remoting scenario, you will not be able to run most of the powershell cmdlets. [...] Yes, this does mean that you will not be able to run cmdlets like Where-Object and .PS1 scripts in the Remote Runspace.
Is that a limitation? I don’t think so. We can very easily get around it by create a new Session and Importing it.
所以你需要像这样:
PSCredential creds = new PSCredential(userName, securePassword);
System.Uri uri = new Uri("http://Exchange-Server/powershell?serializationLevel=Full");
Runspace runspace = RunspaceFactory.CreateRunspace();
PowerShell powershell = PowerShell.Create();
PSCommand command = new PSCommand();
command.AddCommand("New-PSSession");
command.AddParameter("ConfigurationName", "Microsoft.Exchange");
command.AddParameter("ConnectionUri", uri);
command.AddParameter("Credential", creds);
command.AddParameter("Authentication", "Default");
powershell.Commands = command;
runspace.Open(); powershell.Runspace = runspace;
Collection<PSSession> result = powershell.Invoke<PSSession>();
powershell = PowerShell.Create();
command = new PSCommand();
command.AddCommand("Set-Variable");
command.AddParameter("Name", "ra");
command.AddParameter("Value", result[0]);
powershell.Commands = command;
powershell.Runspace = runspace;
powershell.Invoke();
powershell = PowerShell.Create();
command = new PSCommand();
command.AddScript("Import-PSSession -Session $ra");
powershell.Commands = command;
powershell.Runspace = runspace;
powershell.Invoke();
# now you can use remote PS like it's local one
从 Exchange Server 2010 开始,您需要使用远程 PowerShell 会话,而不是直接添加 exchange PowerShell 管理单元(由于在 exchange 2010 中使用 RBAC 而不是 ACL)。 因此,您需要创建新的 PowerShell 会话(使用 New-PSSession),然后导入它(使用 Import-PSSession)。 您可以使用这样的代码远程执行 PowerShell 命令:
void ExecutePowerShellUsingRemotimg()
{
RunspaceConfiguration runspaceConfig = RunspaceConfiguration.Create();
PSSnapInException snapInException = null;
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfig);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
string serverFqdn = "FQDN of you server";
pipeline.Commands.AddScript(string.Format("$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://{0}/PowerShell/ -Authentication Kerberos", serverFqdn));
pipeline.Commands.AddScript("Import-PSSession $Session");
pipeline.Commands.AddScript("your PowerShell script text");
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
StringBuilder sb = new StringBuilder();
if (pipeline.Error != null && pipeline.Error.Count > 0)
{
// Read errors
succeeded = false;
Collection<object> errors = pipeline.Error.ReadToEnd();
foreach (object error in errors)
sb.Append(error.ToString());
}
else
{
// Read output
foreach (PSObject obj in results)
sb.Append(obj.ToString());
}
runspace.Dispose();
pipeline.Dispose();
}