PowerShell: Convert Local Path to UNC Path

function convertLocalToUnc($localPath,$computername){    
    $uncPath=.{$x=$localPath -replace "^([a-zA-Z])\:","\\$computername\`$1`$";
                if($x -match '\\$'){return $x.Substring(0,$x.length-1)}else{return $x}
                }
    $validLocal=if($localPath){test-path $localPath -ErrorAction SilentlyContinue}else{$false}
    $validUnc=if($uncPath){test-path $uncPath -ErrorAction SilentlyContinue}else{$false}
    if($validUnc){write-host "$uncPath is reachable, using credentials of $(whoami)"}
    else{write-warning "$computername is unreachable, using credentials of $(whoami)"}
    return $uncPath
}
# Usage Example
PS C:\Windows\system32> convertLocalToUnc $defaultBackupDirectory $sqlServer
\\sqlSherverXOXO\C$\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup is reachable, using credentials of intranet\bowow

2 thoughts on “PowerShell: Convert Local Path to UNC Path”

Leave a Reply

Your email address will not be published. Required fields are marked *