首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在powershell中使用重试和循环处理网络映射?

如何在powershell中使用重试和循环处理网络映射?
EN

Stack Overflow用户
提问于 2022-01-04 04:23:05
回答 1查看 188关注 0票数 0

我想绘制一个网络。如果映射失败,我需要使用retry。在最大限度地重试之后,它将失败并继续到另一个进程。如果映射通过,那么也继续到另一个进程。我试过这样做,但似乎重试不起作用。一旦映射失败,它不执行网络映射过程,只处理循环。任何人都可以给我主意。

代码语言:javascript
复制
$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) {
}

非常感谢你的建议。感谢你!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-05 11:36:38

这两个注释都是有效和有用的(在循环之外的com对象和、使用)。

现在,我测试了您的脚本,它应该可以实现您的期望。只有当网络驱动器已经在使用时,它才会忽略这一点。要用最少的修改来捕获它,您可以简单地在循环开始之前添加此检查:

代码语言:javascript
复制
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
}

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

代码语言:javascript
复制
$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
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70574082

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档