【问题标题】:How to add maximum looping in Powershell?如何在 Powershell 中添加最大循环?
【发布时间】:2021-12-21 03:34:09
【问题描述】:

我想映射网络。如果映射失败,我需要使用重试,最大重试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

任何人都可以提供帮助,非常感谢。谢谢

【问题讨论】:

    标签: powershell loops network-drive retry-logic


    【解决方案1】:

    有很多方法可以解决这个问题,这是一种使用script block的方法,请注意,此示例仅适用于您使用Write-Host,它的输出转到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
    }
    

    【讨论】:

    • 嗨,谢谢@Santiago Squarzon,但它仍然是无限循环。
    • @Cheries 两种选择都对我有用,我做了一些编辑,你可能使用的是旧的代码副本。
    • @Cheries 捕获块上的Write-Host $Message 未被捕获,因此如果您使用Write-Warning $_.Exception.Message,您应该在控制台上看到它
    • 好的。谢谢
    • HI @Santiago Squarzon,我发现了一个问题,我使用你的第二种方式回答,但我的期望是,如果动作是真的,我不需要停止这个过程,因为我在映射网络之后有另一个进程。第二个问题,如果映射失败,我还有另一个进程,哪个错误处理,错误处理将处理5次与总重试相同,但我的期望,错误处理将在重试完成后处理,而不是循环。我希望你能帮我弄清楚。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多