ForbesLindesay
ForbesLindesay

Reputation: 10712

Connect to exchange asyncronously using powershell

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?

Upvotes: 0

Views: 708

Answers (2)

ForbesLindesay
ForbesLindesay

Reputation: 10712

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.

Upvotes: 1

CB.
CB.

Reputation: 60958

try this:

Start-Job -scriptblock {Param ($cred) CONNECT-MSOLService -credential $Cred} -ArgumentList $cred

Upvotes: 1

Related Questions