Speed up Test-Connection before Foreach

后端 未结 2 1436
萌比男神i
萌比男神i 2021-01-07 03:38

I made a script to check if users desktop folder are under the cuota limitation, if they\'re under the cuota limitation the backup to the server will be done correctly.

2条回答
  •  孤城傲影
    2021-01-07 04:03

    To speed up your script you need to run the checks in parallel (as others have already mentioned). Put your checks and the worker code in a scriptblock:

    $sb = {
        Param($computer, $username)
    
        if (Test-Connection -Quiet -Count 2 $computer) { return }
    
        $w7path = "\\$computer\c$\users\$username\desktop"
        $xpPath = "\\$computer\c$\Documents and Settings\$username.TUITRA..."
    
        if (Test-Path $W7path) {
            #...
        } elseif (Test-Path $xpPath) {
            #...
        } else {
            #...
        }
    }
    

    Then run the scriptblock as parallel jobs:

    $csv | ForEach-Object {
        Start-Job -ScriptBlock $sb -ArgumentList $_.PCName, $_.User
    }
    
    # wait for completion
    do {
        Start-Sleep -Milliseconds 100
    } while (Get-Job -State 'Running')
    
    # cleanup
    Get-Job | ForEach-Object {
        Receive-Job -Id $_.Id
        Remove-Job -Id $_.Id
    } | Out-File $outputReport
    

    Use a queue if you need to limit the number of parallel jobs.

提交回复
热议问题