Powershell foreach(每10批)

我有以下代码可从合作伙伴中心获取数据

$custIDs = Get-microsoftPartner
foreach ($custID in $custIDs)

{
 Export-microsoftData -CustomerId $custID
 }

在这个foreach循环中,我有成千上万的{{​​1}},因此我想在10步中运行此命令,在第一次迭代中先获取前10个客户,再在接下来的10个中依次类推。

我有满足我想要的代码,但是它比一次循环遍历所有客户的速度慢得多(而且工作也很慢)

CustomerID

有没有更有效的方法?

zhuangting 回答:Powershell foreach(每10批)

[$i..(($i+= $group) - 1)]是错误的。这会使除第一个批次之外的每个批次的起始$i都设置得太低,这意味着您要做的工作过多而不必要。

您的意思是[($i * $group)..(($i+1) * $group - 1)],即类似这样的

$batches = for ($i = 0; $i -lt $custIDs.Count / $group; $i++) {,$custIDs[($i * $group)..(($i+1) * $group - 1)]
}

请注意在开始时使用,,以确保获得嵌套数组。


话虽如此,我将重组Export-MicrosoftOrganizationData。主要是因为检索对象和导出对象是两件事,因此不应在同一功能中完成它们。

这使一切变得更简单-不再需要beginend块,不再需要中间数组,并且该函数(我们称之为Get-MicrosoftOrganizationData)整体上变得更加通用:

function Get-MicrosoftOrganizationData {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory,ValueFromPipeline)] # CustomerId from Microsoft Partner Center
        [string[]]$CustomerId
    )
    @($CustomerId) | ForEach-Object {
        $Organization = [Organization]::new()
        $Organization.PopulateMicrosoftData($_)
        $Organization
    }
}

Export-Csv调用的复杂程度不足以将其塞入函数中:

$custIDs = Get-MicrosoftPartnerCustomers
$orgData = $custIDs | Get-MicrosoftOrganizationData
$orgData | Export-Csv -NoTypeInformation -Delimiter "," -Path .\TestOutputOrg.csv

基本上,您甚至可以将所有内容都放在一行上。

总的来说,从输入中提取X批次可能对于测试事物很有用,但是无论如何如果要处理 all 个ID,这不是一个有用的策略。

本文链接:https://www.f2er.com/3144743.html

大家都在问