Powershell: Checking if Network Drive exists, if not, map it then double check

Viewed 22514

I am trying to write a simple script to check if a network drive is available, map it if it isn't, then double check the mapping worked (to report any issues like the account mapping it has accidentally expired etc). If it fails at the double check, it will send an email, otherwise it reports all ok.

I cannot get the double check to work. I think I have my statements wrong?

$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"}
2 Answers

I like James' answer but want to explain why you're having this issue. The reason your double check is failing is that you actually only check for the Path a single time.

In the beginning of the code, you check to see if the path exists on these two lines

$Networkpath = "X:\Testfolder" 
$pathExists = Test-Path -Path $Networkpath

The variable $pathExists is created at this point and stores the outcome from that point in time. That's why your double check if failing later in the code, it's actually using the same output from the first time.

The code continues to test if the path exists, and if not, then creates the path.

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

What you should do is add one more test here, then you'll know the drive already exists.


I added the extra test for you and slightly tweaked the flow through the script, with a Write-Host output for each branch. Here's the completed code.

$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"}

You can use an if within an if (nested if) to perform a check after the drive has been mapped.

I also changed the logic of the first check so it doesn't use -not as it makes the code simpler.

$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"
    }
}
Related