Tags

,


I had a bit of a play today with Trace-Command so thought I’d post a simple but useful example here that also illustrates an issue with UNC paths that you may not have come across.

Try the following:

Set-Location -Path 'HKLM:'
Get-ChildItem -Path '\\localhost\c$'

The result may surprise you:
UNC Fail
The quick answer is that the current location has to be a drive using the FileSystem PSProvider. If we didn’t know that fact, we could uncover the answer with Trace-Command:

Trace-Command -Expression {Get-ChildItem -Path '\\localhost\c$'} -PSHost -Name PathResolution

-Expression is the expression you wish to trace and as such is a scriptblock enclosed in curly brackets.
-PSHost directs the trace output to the PowerShell host so you can see it.
-Name is an array of PowerShell component names that can be traced. We can see these with the following code:

Get-TraceSource | Select-Object -Property Name,Description

I’ll let you look those up for yourself, but the item that stood out in the context of troubleshooting this error was named PathResolution and had the description “Traces the path resolution algorithm.

Here’s the output from tracing the original problematic code:
Traced - Fail
We can see here that it is interpreting the UNC Path in the context of the Microsoft.PowerShell.Core\Registry PSProvider (ie the “Registry” provider).
If my current location had been C:\ then it would have been in the context of the Microsoft.PowerShell.Core\FileSystem PSProvider and the Get-ChildItem would have been successful.

So, what if you can’t guarantee what the current location is in advance of accessing a UNC path? The answer is to qualify the UNC path with the provider name followed by a double-colon:

Get-ChildItem -Path 'FileSystem::\\localhost\c$'

This now works whether you’re already in a FileSystem drive or not.
And yes, you could even use the full PSProvider name:

Get-ChildItem -Path 'Microsoft.PowerShell.Core\FileSystem::\\localhost\c$'

Here’s part of a trace with a provider-qualified UNC path showing that the path is now being interpreted correctly in the context of the FileSystem provider:
Traced - Win

Advertisements