Converting a path to UNC path doesn’t really take that many lines of code, but having recently been in a project where I needed to do this a lot, I got tired of copy-pasting the same 2-3 lines of code back and forth, and decided to create a helper function out of it.

It’s by no means perfect, and at the moment only deals with UNC paths where you have a local path and a computer name, where you want a UNC path in the format of \\computer\drive$\path\to\somewhere\

Hopefully it will be helpful to someone else as well.

function ConvertTo-UNCPath {
<#
.SYNOPSIS
Convert a path to UNC path
.DESCRIPTION
Convert a path to UNC path
.NOTES
Author: Øyvind Kallstad
Date: 26.10.2015
Version: 1.0
.INPUTS
System.String
.OUTPUTS
System.String
.LINK
https://communary.wordpress.com/
#>
[CmdletBinding()]
param (
[Parameter(Position = 2, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[string] $Path,
[Parameter(Position = 1)]
[ValidateNotNullOrEmpty()]
[string] $ComputerName
)
$pathRoot = [System.IO.Path]::GetPathRoot($Path)
Write-Output ("\\$($ComputerName)$(($Path).Replace($pathRoot, "\$($Path[0])$\"))")
}

2 comments

    1. haha.. yes, I know what you mean. Did it for the longest time, before I got fed up with it. Glad you liked it! 😀

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s