我正在使用C#发送与Exchange交互的PowerShell命令。我有一个名为initconnection
的方法,它建立了与Exchange的连接。通过C#交换PowerShell命令
我有另一种方法,当我点击一个按钮后,会在连接建立后向powershell发送命令。但是我无法继续创建的连接。当我尝试运行一个命令时说它没有找到命令。更可能是因为它没有交换cmdlet。
Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript("Set-ExecutionPolicy Unrestricted -Scope process -Force;$password = ConvertTo-SecureString -AsPlainText -Force " + password + ";$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist " + username + ",$password;$LiveCred = Get-Credential -Credential $mycred; $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic –AllowRedirection; Import-PSSession $Session");
// pipeline.Commands.Add("Out-String");
pipeline.Invoke();
mpeAdd.Hide();
这是创建连接的initconnection方法。
protected void Get_Mailboxes(object sender, EventArgs e) {
PowerShell powershell = PowerShell.Create();
PSCommand command = new PSCommand();
command = new PSCommand();
command.AddCommand("Get-Mailbox");
powershell.Commands = command;
powershell.Runspace = runspace; //Also it says runsapce doesn't exist in this context.
Collection<PSObject> commandResults = powershell.Invoke();
StringBuilder sb = new StringBuilder();
ArrayList boxesarray = new ArrayList();
foreach (PSObject ps in commandResults)
{
boxesarray.Add(ps.Properties["Alias"].Value.ToString());
}
boxes.DataSource = boxesarray;
boxes.DataBind();
}
这是我在创建连接后单击按钮时调用的方法,但它不起作用。