Home » Questions » Computers [ Ask a new question ]

Get the current UNC path from a local path in powershell

Get the current UNC path from a local path in powershell

Assuming I have a mapped drive M:\ to \\SomeServer\SomeShare and in powershell I'm in the folder M:\SomeFolder how do I convert that to a UNC path, i.e. \\SomeServer\SomeShare\SomeFolder.

Asked by: Guest | Views: 27
Total answers/comments: 3
Guest [Entry]

"I'm fairly new to PowerShell, so the code below may be poor quality. However, it should get the information you want:

$currentDirectory = Get-Location
$currentDrive = Split-Path -qualifier $currentDirectory.Path
$logicalDisk = Gwmi Win32_LogicalDisk -filter ""DriveType = 4 AND DeviceID = '$currentDrive'""
$uncPath = $currentDirectory.Path.Replace($currentDrive, $logicalDisk.ProviderName)

$uncPath should contain the UNC path that you are looking for."
Guest [Entry]

"I realize this is an old question, but I wanted to share another way to accomplish this:

$drive = Get-PSDrive -Name (get-location).Drive.Name
$root = if($drive.DisplayRoot -ne $null){$drive.DisplayRoot} else {$drive.Root}
Join-Path -Path $root -ChildPath $drive.CurrentLocation

Get-PSDrive will pull back all the information about a drive (name, used/free space, provider, root and current location) and passing the Name parameter as the current drive letter (using get-location) allows this to work in multiple scenerios (this will also pull back information on local drives on the machine).

In order to make it work on both local and mapped drives the comparison is done to populate $root with the drive letter or network location. the .Root will send back the drive letter, and the .DisplayRoot will pull back the network path (null if it is a local path, which is the reason for the comparison)

Using Join-Path, then you can pull together the path, which will return a drive letter and current location if it's a local path, network path and current location if it's a mapped drive."
Guest [Entry]

"$CurrentFolder = ""H:\Documents""

$Query = ""Select * from Win32_NetworkConnection where LocalName = '"" + $CurrentFolder.Substring( 0, 2 ) + ""'""
( Get-WmiObject -Query $Query ).RemoteName

$Tst = $CurrentFolder.Substring( 0, 2 )
( Get-WmiObject -Query ""Select * from Win32_NetworkConnection where LocalName = '$Tst'"" ).RemoteName"