我在 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.);