我在C#中有以下代碼,我用它來連接到通過PowerShell進行交換。PowerShell和在C交換#
以下代碼可以正常工作,但是爲了使用交換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
是我的第一個命令的輸出。但是我不知道我怎麼可以聲明輸出變量$會話或喜歡的東西:
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.);
你有沒有解決過這個問題? 使用powershell__2作爲PowerShell的= PowerShell.Create() command.AddScript( 「進口的PSSession -Session $ RA」) powershell__2.Commands =命令 powershell__2.Runspace =: – Kjensen