【问题标题】:How to handle a network mapping with retry and looping in powershell?如何在powershell中通过重试和循环处理网络映射?
【发布时间】:2022-01-04 04:23:05
【问题描述】:

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

$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) {
}

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

【问题讨论】:

  • 您知道 PowerShell 有一个专用的 cmdlet 用于映射网络驱动器,称为 New-PSDrive?
  • 另外,不要在没有释放它们的情况下循环创建无数 ComObjects。最终,您将耗尽可用内存..

标签: powershell loops mapping retry-logic


【解决方案1】:

两个 cmets 都是有效且有用的(循环外的 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
    }
}

【讨论】:

    猜你喜欢
    • 2020-04-30
    • 2022-07-22
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    相关资源
    最近更新 更多