2017-10-04 109 views
2

我想写一个简单的脚本来检查网络驱动器是否可用,映射它,如果它不是,然后仔细检查映射工作(报告任何问题,如帐户映射意外过期等)。如果双重检查失败,它会发送一封电子邮件,否则它会报告一切正常。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"} 

回答

1

我喜欢詹姆斯的回答,但想解释为什么你有这个问题。您的重复检查失败的原因是您实际上只检查一次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"} 
+0

这很完美!非常感谢你的扩展解释! – Adam

2

您可以使用ifif(嵌套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" 
    } 
} 
相关问题