3

我在 C# 中有以下代码,用于通过 powershell 连接交换。

以下代码可以正常工作,但是我还需要一个命令才能使用交换 cmdlet。

这是我现在拥有的代码。

Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
PowerShell powershell = PowerShell.Create();

PSCommand command = new PSCommand();
command.AddCommand("New-PSSession");
command.AddParameter("ConfigurationName", "Microsoft.Exchange");
command.AddParameter("ConnectionUri", new Uri("https://ps.outlook.com/powershell/"));
command.AddParameter("Credential", creds);
command.AddParameter("Authentication", "Basic");
command.AddParameter("AllowRedirection");

powershell.Commands = command;

try
{
    runspace.Open();
    powershell.Runspace = runspace;

    Collection<PSObject> commandResults = powershell.Invoke();

    StringBuilder sb = new StringBuilder();

    foreach (PSObject ps in commandResults)
    {
        sb.AppendLine(ps.ToString());
    }

    sb.AppendLine();

    lbl.Text += sb.ToString();
}
finally
{
    // dispose the runspace and enable garbage collection
    runspace.Dispose();
    runspace = null;
    // Finally dispose the powershell and set all variables to null to free
    // up any resources.
    powershell.Dispose();
    powershell = null;
}

我的问题是我仍然需要运行第一个命令的输出import-pssession $session所在的命令。$session但是我不确定如何将该输出声明为变量 $session 或类似的东西:

 PSCommand command = new PSCommand();
 command.AddCommand("Import-PSSession");
 command.AddParameter("Session", #Not sure how to put session info which is what the first command produces into here.);
4

2 回答 2

3

您可以尝试使用创建远程运行空间来代替,下面给出了一个示例。您可以参考以下文章http://msdn.microsoft.com/en-us/library/windows/desktop/ee706560(v=vs.85).aspx

string schemaURI = "http://schemas.microsoft.com/powershell/Microsoft.Exchange";
Uri connectTo = new Uri("https://ps.outlook.com/powershell/");
PSCredential credential = new PSCredential(user,secureStringPassword ); // the password must be of type SecureString
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(connectTo,schemaURI, credential);
connectionInfo.MaximumConnectionRedirectionCount = 5;
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;

try
{
    Runspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo);
    remoteRunspace.Open();
}
catch(Exception e)
{
    //Handle error 
}
于 2012-10-07T02:25:33.463 回答
1

尝试以下技术网博客 http://blogs.technet.com/b/exchange/archive/2009/11/02/3408653.aspx中的“使用本地运行空间的远程请求(编写远程类脚本)”部分

我相信你想要实现的是:

    // Set the runspace as a local variable on the runspace
    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();

其中 result[0] 是创建的第一个远程会话的结果。让我知道这是否有帮助。

于 2012-07-31T13:26:24.593 回答