Sometimes when writing PowerShell scripts we encounter an issue where PowerShell cannot locate UNC paths correctly.

PowerShell Cannot Locate UNC Paths

Take the following chunk of code; make sure you change the UNC path to a valid path, and run it in a PowerShell session:

Set-Location C:  
write-host "Directory Found: " + (test-path "\\alkane\unc\path")  
Set-Location HKLM:  
write-host "Directory Found: " + (test-path "\\alkane\unc\path")  
Set-Location C:  
write-host "Directory Found: " + (test-path "\\alkane\unc\path")

You will most likely see that the results returned are true, false and then true for the exact same UNC path!  Now run the following:

Get-PSDrive

and you will see output similar to the following:get-psdriveIf you review the Provider for each PSDrive you will notice that when our script didn’t work, it was because we set the location to a non-filesystem PSDrive (we set it to the ‘Registry’ provider drive called HKLM).

What is happening here is that when we use Test-Path, Move-Item or indeed any other FileSystem-related cmdlet, PowerShell will try to use the current PSDrive provider (in this case the Registry provider) to locate the file.  And hence it doesn’t work.

There are two solutions here:

Changing the PSDrive Provider

The clunky way is to change the PSDrive provider to the FileSystem as and when required (and then change it back to the previous PSDrive afterwards):

try {  
  Push-Location (Get-Location -PSProvider FileSystem)
  write-host "Directory Found: " + (test-path "\\alkane\unc\path") 
} finally {   
   Pop-Location
}

Add FileSystem:: to UNC Paths

The optimal approach is to prefix any UNC paths with FileSystem:: forcing PowerShell to use the FileSystem provider to locate the UNC path:

write-host "Directory Found: " + (test-path "Filesystem::\\alkane\unc\path")

 

PowerShell Cannot Locate UNC Paths
Comments have now been disabled. If you have a question to ask about this post please ask the community!