我想绘制一个网络。如果映射失败,我需要使用retry。在最大限度地重试之后,它将失败并继续到另一个进程。如果映射通过,那么也继续到另一个进程。我试过这样做,但似乎重试不起作用。一旦映射失败,它不执行网络映射过程,只处理循环。任何人都可以给我主意。
$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) {
}非常感谢你的建议。感谢你!
发布于 2022-01-05 11:36:38
这两个注释都是有效和有用的(在循环之外的com对象和、使用)。
现在,我测试了您的脚本,它应该可以实现您的期望。只有当网络驱动器已经在使用时,它才会忽略这一点。要用最少的修改来捕获它,您可以简单地在循环开始之前添加此检查:
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
}
}https://stackoverflow.com/questions/70574082
复制相似问题