我正在使用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();
}
這是我在創建連接後單擊按鈕時調用的方法,但它不起作用。