【问题标题】:Looping through Exchange Online clients in PowerShell. Faster way to do this?在 PowerShell 中循环通过 Exchange Online 客户端。更快的方法来做到这一点?
【发布时间】:2018-05-03 23:27:52
【问题描述】:

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

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

【问题讨论】:

    标签: powershell office365 powershell-remoting


    【解决方案1】:

    使用 Start-Job

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

    对于您的每个租户,您可以启动一个作业并跟踪创建的作业对象,例如

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

    一旦你开始工作,找到一种方法等待它们完成并收集代码可能吐出的任何输出。

    【讨论】:

    • 这里推荐使用 PoshRsJob 模块,Start-Job 会在后台创建一个 PowerShell.exe,如果用户太多,会消耗太多系统资源。 Start-RSJob 使用运行空间。
    【解决方案2】:

    这里我推荐使用PoshRsJob模块,Start-Job会在后台创建一个PowerShell.exe,所以如果用户太多,会消耗太多的系统资源。

    Start-RSJob 使用运行空间。

    【讨论】:

    • 我以后会试试这个,但是滥用系统资源不是问题,使用作业设置起来超级简单。谢谢!
    猜你喜欢
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2014-03-10
    相关资源
    最近更新 更多