Get the current UNC path from a local path in powershell

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.


For any one interested in the RunAs script for StExBar it is:

param([string] $username)

$path = Get-Location
$currentDrive = Split-Path -qualifier $path
$logicalDisk = Get-WmiObject Win32_LogicalDisk -filter "DeviceID = '$currentDrive'"

if ($logicalDisk.DriveType -eq 4)
{
    $path = Join-Path $logicalDisk.ProviderName (Split-Path -NoQualifier $path)
}

$systemroot = [System.Environment]::SystemDirectory

&"$systemroot\runas.exe" /user:$username "$systemroot\windowspowershell\v1.0\powershell.exe -NoExit -Command \`" &{ Set-Location '$path' }\`""

And the command line in StExBar is:

C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -Command "&{ &'%homedrive%%homepath%\RunAs.ps1' 'domain\username' }"

Replace the path with where ever you keep the RunAs.ps1 script, I like to store mine in the root of my home folder.


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.

Tags:

Powershell