Watch Out With UNC Paths!

by Aug 4, 2014

All PowerShell versions

Many cmdlets can deal with UNC paths, but using UNC paths can produce flaky scripts. Take a look at this:

PS> Test-Path -Path \\127.0.0.1\c$
True

It returns true, the UNC path exists. Now change the current drive to a non-Filesystem drive, and try again:

S> cd hkcu:\

PS> Test-Path -Path \\127.0.0.1\c$
False 

The very same path now yields false. That’s because a UNC path contains no drive letter, and PowerShell needs drive letters to assign the correct provider. If a path does not contain a drive letter, PowerShell assumes the provider of the currently selected drive. So if you change the current directory to the Registry, PowerShell tries to find the UNC path there, and fails.

Even worse, for some unknown reason, when you map drives using “net use”, PowerShell may or may not get confused when you later check this drive with cmdlets.

The solution is simple, though: when you use UNC paths with cmdlets, always prepend the UNC path with the correct provider name. This will eliminate the problem:

PS> Test-Path -Path FileSystem::\\127.0.0.1\c$
True

PS> cd hkcu:\

PS> Test-Path -Path \\127.0.0.1\c$
False

PS> Test-Path -Path FileSystem::\\127.0.0.1\c$
True

If you have trouble with drive letters produced by “net use”, apply the same fix, and prepend the path with “FileSystem::”. The problem will immediately go away.

Twitter This Tip! ReTweet this Tip!