We have two PSSessions that need to be established and imported into the current session before our script can continue. Both steps require about 10 - 15 seconds each for a total of 20 - 30 seconds when run in series.
Is it possible to run New-PSSession in a separate runspace and then somehow import that established session into the parent process?
For example change from this:
New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri ("https://$($service)/PowerShell/") -Credential $Credential -Authentication Basic -AllowRedirection -ErrorAction Stop
New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $Credential -Authentication Basic -AllowRedirection -ErrorAction Stop
To possibly something like this (warning this doesn't work):
$credential = Get-Credential
$scriptblock =
{
param ([string]$Credential)
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $Credential -Authentication Basic -AllowRedirection -ErrorAction Stop
return $session
}
$shell = [PowerShell]::Create().AddScript($scriptblock).AddParameter($credential)
$job = $shell.BeginInvoke()
$result = $shell.EndInvoke($job)
Import-PSSession $result
The ultimate goal is to make this take less time, the idea being if we use New-PSSession in parallel it completes in 10 - 15 seconds instead of 20 - 30 seconds in series. I'd be happy with any answer that accomplishes this, it doesn't need to be using runspaces.
EDIT: Added goals