使用PowerShell异步连接到交换

时间:2011-09-26 14:16:46

标签: powershell asynchronous exchange-server office365

我有以下代码使用powershell连接到我的Office 365帐户:

$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"

但由于这有效连接两次,一次使用new-pssession,一次使用connect -MSOLService,它应该可以同时进行,例​​如:

$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"

但这实际上并不起作用(我猜这是变量范围的一个问题?这可能吗/我应该怎么做?

2 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:1)

我得出的结论可能是不可能的。我认为问题是登录命令会修改它们运行的​​上下文,但如果它们是在异步作业中完成的,则上下文是不同的。