我喜欢詹姆斯的回答,但想解释为什么你有这个问题。您的重复检查失败的原因是您实际上只检查一次Path。
在代码的开始,你检查,看看是否在这两条线
$Networkpath = "X:\Testfolder"
$pathExists = Test-Path -Path $Networkpath
变量$pathExists
在这一点上并保存结果从那个时间点创建所在的路径。这就是为什么你仔细检查,如果在代码后面失败,它实际上是从第一次使用相同的输出。
代码继续测试路径是否存在,如果不存在,则创建路径。
If (-not ($pathExists)) {
(new-object -com WScript.Network).MapNetworkDrive("X:","\\Server-01\Share")
}
你应该做的是在这里增加一个测试,然后你就会知道驱动器已经存在。
我添加了额外的测试,为您和调整了小幅通过脚本的流程,用Write-Host
输出为每个分支。这是完整的代码。
$Networkpath = "X:\Testfolder"
$pathExists = Test-Path -Path $Networkpath
If (-not ($pathExists)) {
(new-object -com WScript.Network).MapNetworkDrive("X:","\\Server-01\Share")
}
else {
Write-host "Path already existed"
Return #end the function if path was already there
}
#Path wasn't there, so we created it, now testing that it worked
$pathExists = Test-Path -Path $Networkpath
If (-not ($pathExists)) {
Write-Host "We tried to create the path but it still isn't there"
#Insert email code here
}
ELSE {Write-Host "Path created successfully"}
这很完美!非常感谢你的扩展解释! – Adam