How to pause a foreach PowerShell loop

那年仲夏 提交于 2021-01-28 04:50:44

问题


I have created this simple script below to loop through a file containing a list of users and apply quota rules for each user in the file.

It works, but during processing it fails sometimes as I believe the large number of users in the text file blocks access at times. Is there a way to get the loop to pause for 5 - 10 seconds after each iteration of the foreach loop or after five iterations of the foreach loop until the filer has updated those quotas completely and then move on to the next user in the file?

ForEach ($adname in Get-Content "C:\Users\mick\Desktop\scripts\staff.txt")
{
    Invoke-NcSsh -Command "volume quota policy rule create -vserver FS-ONE -policy-name default -volume data -type user -target $adname -qtree """" -user-mapping off -disk-limit 3GB -soft-disk-limit 2GB -threshold 3GB"
}

Start-NcQuotaResize -vserver FS-ONE -volume data

回答1:


Use a counter and Start-Sleep:

$UserCount = 0
foreach($adname in Get-Content "C:\Users\mick\Desktop\scripts\staff.txt")
{
    # Sleep 3 seconds every 5 runs
    if(++$UserCount % 5 -eq 0) 
    {
        Start-Sleep -Seconds 3
    }

    Invoke-NcSsh -Command "volume quota policy rule create -vserver FS-ONE -policy-name default -volume data -type user -target $adname -qtree """" -user-mapping off -disk-limit 3GB -soft-disk-limit 2GB -threshold 3GB"
}


来源:https://stackoverflow.com/questions/33948182/how-to-pause-a-foreach-powershell-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!