如何在 powershell 中通过重试和循环处理网络映射?

How to handle a network mapping with retry and looping in powershell?

我想映射一个网络。如果映射失败,我需要使用重试。在最大重试后,它将失败并继续另一个进程。如果映射通过,则也继续另一个过程。我试过这种方式,但似乎重试不起作用。一旦映射失败,不做网络映射处理,只处理循环。 任何人都可以给我想法。

$Stoploop = $false
[int]$Retrycount = "0"
do {
     try {
          
          $net = New-Object -ComObject WScript.Network                   
          $net.MapNetworkDrive("$Path", "\$IP$Folder", $False, "$Server$user", "$pass")
          $Message = "NetWork Mapping : " + $Path + " Mount Successful"
          Write-Host $Message
          $Stoploop = $true
          CaptureLog "$Message`n "
     }
     catch {
          if ($Retrycount -eq 15){
          $Message_1 = "Could not mount after 15 retries." + " $_"
          $Stoploop = $true
          CaptureLog $Message_1
          ErrorHandling $Message_1
          }
          else {

               $Message = "NetWork Mapping : " + $Path + " Trying to mount..."
               Write-Host $Message
               CaptureLog $Message
               Start-Sleep -Seconds 3
               $Retrycount = $Retrycount + 1
          }
     }

}
while ($Stoploop -eq $false) {
}

非常感谢您的建议。赞赏!

两条评论都有效且有用(循环外的 com 对象和 Get-PSDrive、New-PSDrive 用法)。

现在,我测试了您的脚本,它应该可以达到您的预期。唯一没有抓住要点的情况是网络驱动器已在使用中。要以最少的修改捕获此问题,您可以在循环甚至开始之前简单地添加此检查:

if(Test-Path $Path) {
    # if you want to unmap the drive, use: $net.RemoveNetworkDrive($Path, $true) and remove the $Stoploop = $true
    $Message = "NetWork Drive " + $Path + " Already in use..."
    Write-Host $Message
    CaptureLog "$Message`n "
    $Stoploop = $true
}

现在,如果你想简化你的脚本,你可以这样做:

$net = New-Object -ComObject WScript.Network
$retrycount = 0

if(Test-Path $Path) {
    # if you want to unmap the drive, use: $net.RemoveNetworkDrive($Path, $true) and remove the $retrycount = 20
    $Message = "NetWork Drive " + $Path + " Already in use..."
    Write-Host $Message
    CaptureLog "$Message`n "
    $retrycount = 20
}
    
while($retrycount -lt 15) {
    $retrycount += 1
    try {
        $net.MapNetworkDrive($Path, "\$IP$Folder", $False, "$Server$user", $pass)
        $Message = "NetWork Mapping (try $($retrycount)) - $($Path) Mount Successful"
        Write-Host $Message
        CaptureLog "$Message`n "
        $retrycount = 100 # this will exit the loop and indicate successful mapping
    } catch {
        $Message = "NetWork Mapping (try $($retrycount)) - $($Path) Mount failed: $($_.Exception.Message.Replace("`n",''))"
        Write-Host $Message
        CaptureLog "$Message`n "
        Start-Sleep -Seconds 3
    }
}