通过PowerShell中的Exchange Online客户端进行循环。更快的方法吗?

时间:2017-11-20 16:56:16

标签: powershell office365 powershell-remoting

我确定这是一个非常正常的情况,但我有一些情况需要循环访问我的客户端并通过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
}

这可能是我在文档中遗漏的内容,但是有更快的方法来针对多个会话运行命令吗?目前,它需要很长时间才能连接,当然连接到很多不同的租户时会加起来。

2 个答案:

答案 0 :(得分:2)

使用Start-Job

我不会在这里编写完整的代码,但您可能想尝试为每个客户端/连接创建不同的作业。请参阅Start-Job和类似的cmdlet。目标是并行地旋转其中的一些并等待它们完成。

对于每个租户,您可以开始工作并跟踪创建的Job对象,例如

$jobs = @{}

# create the jobs
foreach($tenant in $tenants) {
   $jobs[$tenant] = Start-Job ...
}

启动作业后,找到一种方法等待它们完成并收集代码可能吐出的任何输出。

答案 1 :(得分:0)

我建议在这里使用PoshRsJob模块,Start-Job在后台创建PowerShell.exe,因此如果用户太多,则会占用过多的系统资源。

Start-RSJob使用运行空间。