Powershell:检查网络驱动器是否存在,如果不存在,映射它然后仔细检查

Ada*_*dam 6 powershell

我正在尝试编写一个简单的脚本来检查网络驱动器是否可用,如果不可用则映射它,然后仔细检查映射是否有效(报告任何问题,如帐户映射已意外过期等)。如果双重检查失败,它将发送一封电子邮件,否则报告一切正常。

我无法进行双重检查。我认为我的陈述有误?

$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"}
Run Code Online (Sandbox Code Playgroud)

Fox*_*loy 6

我喜欢詹姆斯的回答,但想解释一下你为什么会遇到这个问题。您的双重检查失败的原因是您实际上只检查了一次路径。

在代码的开头,你检查这两行是否存在路径

$Networkpath = "X:\Testfolder" 
$pathExists = Test-Path -Path $Networkpath
Run Code Online (Sandbox Code Playgroud)

变量$pathExists在此时创建并存储该时间点的结果。这就是为什么您要仔细检查代码是否稍后失败的原因,它实际上使用的是第一次的相同输出

代码继续测试路径是否存在,如果不存在,则创建路径。

If (-not ($pathExists)) {
(new-object -com WScript.Network).MapNetworkDrive("X:","\\Server-01\Share")
}
Run Code Online (Sandbox Code Playgroud)

您应该做的是在此处再添加一个测试,然后您就会知道该驱动器已经存在。


我为您添加了额外的测试,并稍微调整了脚本的流程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"}
Run Code Online (Sandbox Code Playgroud)


Jam*_* C. 5

您可以在驱动器映射后使用 an ifinside (嵌套 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"
    }
}
Run Code Online (Sandbox Code Playgroud)