Speed up Test-Connection before Foreach

后端 未结 2 1438
萌比男神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 03:58

    test-connection is weirdly fast with the -asjob parameter, pinging about 200 computers in 4 seconds:

    $list = cat hp.txt
    test-connection $list -AsJob ; job | receive-job -wait -AutoRemoveJob
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题