如何创建“重试”连接以连接共享网络?

时间:2019-07-05 05:37:31

标签: powershell share

我要连接到共享文件夹。如果连接之后仍未连接,我想重试连接以共享我想要的文件夹。

我尝试了这段代码。我可以连接到服务器。但是,如果连接有问题,则等待约5秒钟,然后返回未找到网络的信息。

sys.sleep()

我的期望是,我可以先重试连接。直到连接,然后进行下一步。

1 个答案:

答案 0 :(得分:1)

您可以利用循环来执行此操作,在该示例中,do...until

$n = 0
do {
  $net = new-object -ComObject WScript.Network
  $net.MapNetworkDrive("P:", "\\192.168.1.2\Temp\BP", $False, "008", "25")
  $n++
  Write-Host "Attempt no $n"
} until ((Test-Path -Path "P:") -or ($n -ge 30))

# Information about success/failure
if (Test-Path -Path "P:") {
  Write-Host "Connected successfully after $n attempts"
} else {
  Write-Host "Connection failed"
}

为避免无限循环,我添加了计数器$n,并指定在30次尝试后结束循环。可以根据需要随意编辑该号码。

Related article if you want to learn more about loops


编辑:根据评论+聊天讨论,此处的代码将无限期尝试连接,并在失败时不返回任何信息

我个人不推荐这种解决方案,因为它存在无限循环,并且没有有关故障的信息,这可能对调试有用。

$n = 0
do {
  $n++
  $net = new-object -ComObject WScript.Network
  $net.MapNetworkDrive("P:", "\\192.168.1.2\Temp\BP", $False, "008", "25")
  Write-Host "Attempt no $n"
} until (Test-Path -Path "P:")

Write-Host "Connected successfully after $n attempts"

类似的解决方案可以重写为函数(这次使用While循环,因为如果共享已连接,我不希望发生重新连接):

function Check-ConnectionToServer {
$n = 0
while (-not (Test-Path -Path "P:")) {
  $n++
  $net = new-object -ComObject WScript.Network
  $net.MapNetworkDrive("P:", "\\192.168.1.2\Temp\BP", $False, "008", "25")
  Write-Host "Attempt no $n"
}
Write-Host "Connected successfully after $n attempts"
return $true
}

,然后在要确保连接处于活动状态时随时使用它。

# Previous cmdlets
Check-ConnectionToServer
# Next cmdlets