在 PowerShell 中循环访问 Exchange Online 客户端。更快的方法来做到这一点?
Looping through Exchange Online clients in PowerShell. Faster way to do this?
我确信这是一个非常正常的场景,但在某些情况下我需要遍历我的客户端并通过 PowerShell 连接到他们的 Exchange Online 基础设施。目前,我这样做:
# Specifying credentials and connecting to Office 365 module
$Credential = Get-Credential
Connect-MsolService -Credential $Credential
# Getting a list of tenant IDs (clients) used to connect to their environment
$Tenants = (Get-MsolPartnerContract).TenantID.Guid
# Running command against all tenants
ForEach ($Tenant in $Tenants) {
# Get primary domain for the tenant
$Domain = (Get-MsolDomain -TenantId $Tenant `
| Where-Object { `
$_.Name -NotLike "*onmicrosoft.com" -and `
$_.Name -NotLike "*microsoftonline.com" })[0].Name
# Authenticating to Exchange Online for the tenant
$Session = New-PSSession `
-ConfigurationName Microsoft.Exchange `
-ConnectionUri https://outlook.office365.com/powershell-liveid?DelegatedOrg=$Domain `
-Credential $Credential `
-Authentication Basic `
-AllowRedirection
Import-PSSession $Session -ErrorAction 'silentlycontinue'
# Logic goes here...
Remove-PSSession $Session
}
这可能是我刚刚在文档中遗漏的内容,但是有没有更快的方法 运行 针对多个会话执行命令?目前,仅连接就需要很长时间,当连接到许多不同的租户时,这当然会加起来。
使用开始作业
我不会在这里写完整的代码,但您可能想尝试为每个 client/connection 创建不同的 Jobs。请参阅 Start-Job
和类似的 cmdlet。目的是并行旋转其中的一些并等待它们完成。
对于您的每个租户,您可以启动一个作业并跟踪创建的作业对象,例如
$jobs = @{}
# create the jobs
foreach($tenant in $tenants) {
$jobs[$tenant] = Start-Job ...
}
启动作业后,想办法等待它们完成并收集代码可能吐出的任何输出。
这里推荐使用PoshRsJob模块,Start-Job会在后台创建一个PowerShell.exe,所以如果用户太多,会占用太多系统资源。
Start-RSJob 使用运行空间。
我确信这是一个非常正常的场景,但在某些情况下我需要遍历我的客户端并通过 PowerShell 连接到他们的 Exchange Online 基础设施。目前,我这样做:
# Specifying credentials and connecting to Office 365 module
$Credential = Get-Credential
Connect-MsolService -Credential $Credential
# Getting a list of tenant IDs (clients) used to connect to their environment
$Tenants = (Get-MsolPartnerContract).TenantID.Guid
# Running command against all tenants
ForEach ($Tenant in $Tenants) {
# Get primary domain for the tenant
$Domain = (Get-MsolDomain -TenantId $Tenant `
| Where-Object { `
$_.Name -NotLike "*onmicrosoft.com" -and `
$_.Name -NotLike "*microsoftonline.com" })[0].Name
# Authenticating to Exchange Online for the tenant
$Session = New-PSSession `
-ConfigurationName Microsoft.Exchange `
-ConnectionUri https://outlook.office365.com/powershell-liveid?DelegatedOrg=$Domain `
-Credential $Credential `
-Authentication Basic `
-AllowRedirection
Import-PSSession $Session -ErrorAction 'silentlycontinue'
# Logic goes here...
Remove-PSSession $Session
}
这可能是我刚刚在文档中遗漏的内容,但是有没有更快的方法 运行 针对多个会话执行命令?目前,仅连接就需要很长时间,当连接到许多不同的租户时,这当然会加起来。
使用开始作业
我不会在这里写完整的代码,但您可能想尝试为每个 client/connection 创建不同的 Jobs。请参阅 Start-Job
和类似的 cmdlet。目的是并行旋转其中的一些并等待它们完成。
对于您的每个租户,您可以启动一个作业并跟踪创建的作业对象,例如
$jobs = @{}
# create the jobs
foreach($tenant in $tenants) {
$jobs[$tenant] = Start-Job ...
}
启动作业后,想办法等待它们完成并收集代码可能吐出的任何输出。
这里推荐使用PoshRsJob模块,Start-Job会在后台创建一个PowerShell.exe,所以如果用户太多,会占用太多系统资源。
Start-RSJob 使用运行空间。