How can I convert a UNC Windows file path to a File URI without using any 3rd party tools or by hand?

The simplest approach is to use the .Net URI class from your PowerShell code:

[System.Uri]'\sharepoint.business.com\DavWWWRoot\rs\project 1\document.txt' will give you a URI, and then the "AbsoluteURI" property will give you that as a string. So:

([System.Uri]'\\sharepoint.business.com\DavWWWRoot\rs\project 1\document.txt').AbsoluteUri

will give you what you want.


PowerShell is an excellent way to automate tedious recurring tasks like the above!

Using PowerShell

Converting the above UNC path into a file URI is extremely simple using PowerShell (all versions), and requires only the format and replace operators, for example:

$Path = "\\sharepoint.business.com\DavWWWRoot\rs\project 1\document.txt"

# replace back slash characters with a forward slash, url-encode spaces,
# and then prepend "file:" to the resulting string

# note: the "\\" in the first use of the replace operator is an escaped
# (single) back slash, and resembles the leading "\\" in the UNC path
# by coincidence only

"file:{0}" -f ($Path -replace "\\", "/" -replace " ", "%20")

Which yields the following:

file://sharepoint.business.com/DavWWWRoot/rs/project%201/document.txt

As a Reusable Function

Finally, recurring tasks like the above should be made into PowerShell functions whenever possible. This saves time in the future, and ensures each task is always executed in exactly the same way.

The following function is an equivalent of the above:

function ConvertTo-FileUri {
    param (
        [Parameter(Mandatory)]
        [string]
        $Path
    )

    $SanitizedPath = $Path -replace "\\", "/" -replace " ", "%20"
    "file:{0}" -f $SanitizedPath
}

Once the function has been defined (and loaded into the current PowerShell session), simply call the function by name and provide the UNC path to convert as a parameter, for example:

ConvertTo-FileUri -Path "\\sharepoint.business.com\DavWWWRoot\rs\project 1\document.txt"

There is a simple and safe online converter doing this job: UNC Path to File URI Online Converter.

It is implemented with Javascript and the transformation is done completely in the browser so the path is not submitted to any server.