我正在使用 C# 发送与 Exchange 交互的 PowerShell 命令。我有一个方法叫它initconnection
建立我与 Exchange 的连接。
当我单击一个按钮时,我会调用另一种方法,该按钮将在建立连接后向 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();
}
这是我在创建连接后单击按钮时调用的方法,但它不起作用。