首页 > 解决方案 > Exchange Online 会话和运行空间

问题描述

我需要在运行空间中执行 Get-MailboxStatistics。我可以在线连接到 Exchange。如果我执行“Get-Pssession”,我可以看到 Exchange 会话。但是如何将此 ExchangeOnline 会话传递给运行空间以执行 Get-MailboxStatistics。目前它无法识别运行空间中的 Get-MailboxStatistics 命令。

这是我的代码(这是更大脚本的一部分):

# Connecting to Exchange Online
$AdminName = "hil119"
$Pass = "password"
$cred_cloud = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName, $Pass
Connect-ExchangeOnline -Credential $cred_cloud -Prefix Cloud

# Executing Get-MailboxStatistics in a Runspace
$Runspace = [runspacefactory]::CreateRunspace()
$PowerShell = [powershell]::Create()
$PowerShell.runspace = $Runspace
$Runspace.Open()
[void]$PowerShell.AddScript({Get-MailboxStatistics 'd94589'})
$PowerShell.BeginInvoke()

标签: multithreadingpowershellexchange-serverrunspaceposhrsjob

解决方案


经过几天的研究,我发现您可以在本地系统或远程 Exchange 服务器上运行线程。如果您在本地系统上运行它,则每个线程都需要自己调用 Exchange 会话,但如果您在远程交换系统(onprem 或云)上运行它,您只需获取一次交换会话并将该会话传递给线。您可以使用 Invoke 命令获取远程会话。此外,我最终还是在 Poshjobs 或运行空间中编写了脚本。最终,从我所读到的 Poshjobs 是 Start-job 和运行空间的组合。

所以这里是用于在远程服务器上运行线程的代码片段。使用此脚本,您可以将相同的交换会话传递给所有线程。

Function Func_ConnectCloud
{
$AdminName = "r43667"
$AdminPassSecure = "pass"
$Cred_Cloud = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName, $AdminPassSecure
Connect-ExchangeOnline -Credential $Cred_Cloud
$CloudSession =  Get-PSSession | Where { $_.ComputerName -like "outlook.office365*"}
Return $CloudSession
}

$script_Remote = 
    {
param(
     $Alias,
     $CloudSession
     )

Invoke-Command -session $CloudSession -ArgumentList $Alias  -ScriptBlock {param($Alias); Get-MailboxStatistics $Alias}
    }

$CloudSession = Func_ConnectCloud
$Alias = 'h672892'
$Job1 = Start-RsJob -Name "job_$Alias" -ScriptBlock $ScriptRemote -ArgumentList $Alias, $CloudSession

Receive-RsJob $Job1
Remove-RsJob $Job1

您可以使用此脚本在本地和云上运行线程,尽管在云服务器上运行时,Microsoft 将只允许两个线程。如果您运行两个以上的线程,您的 Exchange 会话将被终止(这与节流不同)。所以如果你有一个云环境,那么最好在本地运行你的线程。在https://powershell.org/forums/topic/connecting-to-office-365-in-psjobs/上特别参考 @postanote 的脚本


推荐阅读