Why doesn't Powershell System.IO.DirectoryInfo with UNC paths work as expected?

58 Views Asked by At

I'm seeing some inconsistent behaviour in PowerShell Core 7.3 with variables of type [System.IO.DirectoryInfo] - the following works as expected:

$dir = [System.IO.DirectoryInfo]'c:\deploy'
$dir.BaseName # returns 'deploy'
$dir.Name # returns 'deploy'
$dir.Parent.Name # returns 'c:\'

But where the assignment is a UNC share, the behaviour isn't as expected:

$target = [System.IO.DirectoryInfo]'\\sharedhost\Deploy'
$target.Name # returns '\\sharedhost\Deploy'
$target.BaseName # returns '\\sharedhost\Deploy'
$target.Parent.Name # returns nothing, checking shows that Parent is null

I would expect $target.Parent to be 'sharedhost' as that's the parent of the Deploy folder, but instead it returns $null.

I suppose I could temporarily map a drive to that share and use that mapping but that's a faff and besides drive-mapping might not be a robust option.

Can anyone please explain why DirectoryInfo doesn't appear to work as expected with UNC paths?

2

There are 2 best solutions below

0
On

Thanks to the answer from @stackprotector, I've realised that I need to distinguish between local paths and UNC paths which must be treated differently.

Casting a full path name to type [URI] means that I can check if a path is a URI:

$pathUri = [URI]'\\sharedhost\Deploy'
$pathUri.IsUnc # returns true
$pathUri.Host # returns 'sharedhost'

Thanks again for all the feedback and help.

0
On

Your expectations are wrong. If you map \\sharedhost\Deploy to a drive, you will see that neither sharedhost nor Deploy will be a parent of it.

It is just how UNC paths are defined:

UNC = "\\" host-name "\" share-name  [ "\" object-name ]

In your case:

  • sharedhost is the hostname, not a (parent) directory
  • Deploy is the sharename, not a directory1

Everything else underneath \\sharedhost\Deploy will be files and directories. So consider \\sharedhost\Deploy like C:\ in your thinking.


1 Deploy may exist as a directory on the file server, but the share does not have to have the same name as the shared directory.