Connect to exchange asyncronously using powershell
-
30-01-2021 - |
Вопрос
I have the following code to connect to my office 365 account using powershell:
$Cred=GET-CREDENTIAL
Write-Host "Connecting..."
IMPORT-MODULE MSONLINE
CONNECT-MSOLService -credential $Cred
$s = NEW-PSSESSION -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $Cred -Authentication Basic -AllowRedirection
$importresults=import-pssession $s
Write-Host "Connected to exchange server"
but since this effectively connects twice, once with new-pssession and once with connect -MSOLService, it ought to be possible to do both simultaneously, e.g.:
$Cred=GET-CREDENTIAL
Write-Host "Connecting..."
IMPORT-MODULE MSONLINE
$j = start-job -scriptBlock { CONNECT-MSOLService -credential $Cred }
$s = NEW-PSSESSION -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $Cred -Authentication Basic -AllowRedirection
$importresults=import-pssession $s
wait-job $j
Write-Host "Connected to exchange server"
But this doesn't actually work (I'm guessing it's an issue with the scope of the variables? Is this possible to do/how should I do it?
Решение 2
I've come to the conclusion this probably isn't possible. I believe the problem is that the login commands modify the context they run in but the context is different if they are done inside an asynchronous job.
Другие советы
try this:
Start-Job -scriptblock {Param ($cred) CONNECT-MSOLService -credential $Cred} -ArgumentList $cred
Не связан с StackOverflow