I have the following C # code that I use to connect to an exchange through powershell.
The following code works fine, but another command is required to use the Exchange cmdlets.
Here is the code I have.
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
{
runspace.Dispose();
runspace = null;
powershell.Dispose();
powershell = null;
}
My problem is that I still need to run the command import-pssession $session, where $sessionis the result of my first command. However, I'm not sure how I can declare this output as a $ session variable or something like:
PSCommand command = new PSCommand();
command.AddCommand("Import-PSSession");
command.AddParameter("Session",
source
share