我正在尝试编写一个简单的脚本来检查网络驱动器是否可用,如果不可用,请对其进行映射,然后仔细检查映射是否起作用(以报告任何问题,例如其帐户映射意外过期等)。如果再次检查失败,它将发送电子邮件,否则报告一切正常。
我无法进行双重检查。我认为我的陈述有误吗?
$Networkpath = "X:\Testfolder"
$pathExists = Test-Path -Path $Networkpath
If (-not ($pathExists)) {
(new-object -com WScript.Network).MapNetworkDrive("X:","\\Server-01\Share")
}
ELSEIF (-not ($pathExists)) {
Write-Host "Something went very wrong"
#Insert email code here
}
ELSE {Write-Host "Drive Exists already"}
最佳答案
我喜欢詹姆斯的回答,但想解释一下您为什么遇到这个问题。双重检查失败的原因是您实际上只检查一次路径。
在代码的开头,您检查路径是否在这两行上
$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 ($pathExists) {
Write-host "Path already existed"
Return #end the function if path was already there
}
else {
(new-object -com WScript.Network).MapNetworkDrive("X:","\\Server-01\Share")
}
#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"}
关于powershell - Powershell:检查网络驱动器是否存在,如果不存在,请映射它,然后仔细检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46565176/