Powershell.Invoke()结果为0。

时间:2018-11-08 16:48:58

标签: c# powershell

我试图在Windows窗体应用程序中运行以下PowerShell命令。但是我的结果总是为零。 (result.Count == 0)。我试图在Powershell ISE中运行命令,但效果很好。有人可以帮忙吗?

string connectionUri = "https://outlook.office365.com/powershell-liveid/";
var passWord = new SecureString();
foreach (char c in "jmfmjxvgtyspzrns".ToCharArray()) passWord.AppendChar(c);            
PSCredential credential = new PSCredential("myEmail@outlook.com", passWord);
Runspace runspace = RunspaceFactory.CreateRunspace();
PowerShell powershell = PowerShell.Create();

PSCommand command = new PSCommand();
command.AddCommand("New-PSSession");
command.AddParameter("ConfigurationName", "Microsoft.Exchange");
command.AddParameter("ConnectionUri", new Uri(connectionUri));
command.AddParameter("Credential", credential);
command.AddParameter("Authentication", "Basic");
powershell.Commands = command;
runspace.Open();
powershell.Runspace = runspace;
Collection<System.Management.Automation.PSObject> result = powershell.Invoke();

1 个答案:

答案 0 :(得分:0)

我知道了。 我加了:

command.AddParameter("AllowRedirection");

现在可以使用。