我正在尝试编写一个简单的脚本来检查网络驱动器是否可用,如果不是,则映射它,然后仔细检查映射是否有效(报告任何问题,如帐户映射它意外过期等) )。如果在双重检查时失败,它将发送一封电子邮件,否则报告一切正常。
我无法进行双重检查。我想我的陈述错了吗?
$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"}
答案 0 :(得分:2)
您可以在if
(嵌套if)中使用if
在映射驱动器后执行检查。
我还改变了第一次检查的逻辑,因此它没有使用-not
,因为它使代码更简单。
$Networkpath = "X:\Testfolder"
If (Test-Path -Path $Networkpath) {
Write-Host "Drive Exists already"
}
Else {
#map network drive
(New-Object -ComObject WScript.Network).MapNetworkDrive("X:","\\Server-01\Share")
#check mapping again
If (Test-Path -Path $Networkpath) {
Write-Host "Drive has been mapped"
}
Else {
Write-Host "Something went very wrong"
}
}
答案 1 :(得分:1)
我喜欢詹姆斯的回答,但想解释为什么你有这个问题。您的双重检查失败的原因是您实际上只检查一次路径。
在代码的开头,检查这两行是否存在路径
$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"}