Search code examples
powershellunc

The best way to get UNC path from local path


I have the path like C:\Program Files\SomeApp, this path resides on the remote host, e.g. \\host1. I'd just like to replace a drive letter with an admin share, e.g. C:\C$ and add to this path a UNC prefix with a host name and get, eventually, the result like this: \\host1\C$\Program Files\SomeApp. A drive letter can have any value, so we can't hardcode it.

I have done it the following way:

$dir = "C:\Program Files\SomeApp"
$hostIp = "10.1.1.1"

$dir -replace '.:',"\\$hostIP\$($(Split-Path -Qualifier $dir).TrimEnd(':'))$"

However, it looks a bit unclear. Please, propose a better solution.


Solution

  • Simply replace drive letter and colon at the beginning of the string with the host part and the drive letter followed by a $. The rest of the path will remain unchanged.

    $dir -replace '^(.):', "\\$hostIp\`$1$"
    

    Escaping the $ in $1 prevents PowerShell from trying to expand the reference to the capturing group as a variable.