multithreading - 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()
解决方案
经过几天的研究,我发现您可以在本地系统或远程 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 的脚本
推荐阅读
- sql - 分析 SQL 查询
- python - C++程序的Python文本解析器?
- python - 逐字节读取二进制数据并使用python提取数据
- jit - Android 7.0 Nougat - 在 ART 中检查 AOT 和 JIT 编译
- robotframework - 我们如何在机器人框架中运行特定的测试用例
- python - 是否可以通过 django-cassandra-engine 连接到多个集群?
- python - Collection.loadTable:在 GEE 中找不到
- python - python - 将嵌套字典拆分为带有子标题的excel
- swift - 如何使我的应用程序表现得像我正在使用 Swift 在运行时更改 Application is agent(UIElement)?
- php - Laravel cviebrock/eloquent-sluggable 如何生成带有名称和记录 ID 的 slug