在c#中创建远程PowerShell会话?

时间:2010-07-09 21:09:50

标签: c# windows powershell exchange-server

我对PS很新,所以我觉得我在这里缺少一些基本的东西。我可以做这样的远程PowerShell会话......

$Session = New-PSSession -ConfigurationName Microsoft.Exchange
                             -ConnectionUri https://remote.com/Powershell
                             -Credential "Domain\Admin"

我想要C#中的等价物,所以我正在尝试这个,但它不起作用......

WSManConnectionInfo connInfo = new WSManConnectionInfo(
   new Uri("https://remote.com/Powershell"),    /* uri */
   "/wtf",                        /* shellUri??? */
   cred);                                       /* ps-credential */

using (Runspace runspace = RunspaceFactory.CreateRunspace(connInfo))
{
    runspace.Open();
    using (PowerShell ps = PowerShell.Create())
    {
        ps.Runspace = runspace;
    }
}

这失败了......

System.Management.Automation.Remoting.PSRemotingTransportException was unhandled
  Message=Connecting to remote server failed with the following error message : The WS-Management service cannot process the request. The resource URI (/wsman) was not found in the WS-Management catalog....

如何将其转换为C#?什么是“shellUri”参数以及如何传达配置名称(在我的情况下是Microsoft.Exchange)?

3 个答案:

答案 0 :(得分:1)

  

http://schemas.microsoft.com/powershell/Microsoft.Exchange

应该适用于shell uri并将上下文放入Exchange配置

答案 1 :(得分:1)

我使用像

这样的东西
int iRemotePort = 5985;
string strShellURI = @"http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
string strAppName = @"/wsman";
AuthenticationMechanism auth = AuthenticationMechanism.Negotiate;

WSManConnectionInfo ci = new WSManConnectionInfo(
    false,
    sRemote,
    iRemotePort,
    strAppName,
    strShellURI,
    creds);
ci.AuthenticationMechanism = auth;

Runspace runspace = RunspaceFactory.CreateRunspace(ci);
runspace.Open();

PowerShell psh = PowerShell.Create();
psh.Runspace = runspace;

通过此操作,您可以访问远程PowerShell会话。使用psh远程运行命令。

答案 2 :(得分:-1)