如何在 Powershell 中添加最大循环?

How to add maximum looping in Powershell?

我要映射网络。映射失败需要重试,最大重试5次。我已经尝试过这种方式,但我不知道如何添加最大重试次数。

Do{
    Try{     
        $net = new-object -ComObject WScript.Network                   
        $net.MapNetworkDrive("$Directory", "\IP$Folder", $False, "$Server$SQL", "$pass")
        $Message = "Mapping : " + $Directory + "Successful"
        Write-Host $Message
        
    }
    Catch{

         $Message= "Mapping : " + $Directory + " Fault" + " $_"
         Write-Host $Message
         # in here there is error handling.
         CallErrorHandlingFunction
    }
}While($? -ne $true)

# in here there is next process after network mapping  succesfull.
CallNextProcess

任何人都可以帮助真的很感激。谢谢

有很多方法可以解决这个问题,这里是使用 script block, note that this example only works because you're using Write-Host which's outputs goes to the Information Stream 的方法,除非重定向 (6>&1),否则不会捕获它的输出。

$action = {
    Try
    {
        $net = New-Object -ComObject WScript.Network                   
        $net.MapNetworkDrive(
            "$Directory", "\IP$Folder", $False, "$Server$SQL", "$pass"
        )
        $Message = "Mapping : " + $Directory + "Successful"
        Write-Host $Message
        $true # => if everything goes right $result = $true
    }
    Catch
    {
        $Message = "Mapping : " + $Directory + " Fault" + " $_"
        Write-Host $Message
        $false # => if fails $result = $false
    }
}

$maxRetries = 5

do { $result = & $action }             # do this
until (-not --$maxRetries -or $result) # until $result is True OR
                                       # $maxRetries reaches 0

老实说,一个更简单的选择:

$maxRetries = 5

1..$maxRetries | ForEach-Object {
    if( & $action ) { break } # => if action = True stop the loop
}