Last active
January 8, 2019 16:51
-
-
Save Trucido/5020ecb30d9df22484f26956f9b9f39d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[CmdletBinding(DefaultParameterSetName = "Path")] | |
[OutputType([string])] | |
Param( | |
[Parameter( | |
Mandatory = $false, | |
ValueFromPipeline = $true, | |
ValueFromPipelineByPropertyName = $true)] | |
[ValidateNotNullOrEmpty()] | |
[Alias("Name","FullName","LiteralPath","LP","PSPath")] | |
$Path | |
) | |
Try{ | |
if(!$Path) { | |
$Path = $pwd.ProviderPath | |
} | |
if((Test-Path $Path)-and(Convert-Path $Path)) { | |
$LiteralPath = Convert-Path $Path | |
}else{ | |
try{ | |
if(Test-Path -IsValid $($pwd.Path + '\' + $Path)){ | |
$LiteralPath = $($pwd.Path + '\' + $Path) | |
}elseif(Test-Path -IsValid $($pwd.Path + $Path)){ | |
$LiteralPath = $($pwd.Path + $Path) | |
}else{return $Path} | |
}catch{return $Path} | |
} | |
}Catch{ | |
if($LiteralPath) { | |
return $LiteralPath | |
}elseif($Path) { | |
return $Path | |
}else{ | |
return | |
} | |
} | |
if($LiteralPath){ | |
Try{ | |
if( ($LiteralPath.Contains('\')) -and -not | |
($LiteralPath.Contains('\ ')) -and -not | |
($LiteralPath.Contains('\\')) ){ | |
Try{ | |
[string]$EscapedPath = [string]::new($LiteralPath).Replace('\','\\') # | sed.exe 's@\\@\\\\@g' | |
if(-not([string]::IsNullOrEmpty($EscapedPath))){ | |
if( ($EscapedPath.Contains('\\\\')) -and -not | |
($EscapedPath.StartsWith('\\\\')) ){ | |
# Handle UNC paths? | |
$EscapedPath = $EscapedPath -Replace '\\\\','\\' | |
} | |
# Handle whitespaces in path. (cygpath and msys2/cygwin utils choke on single quotes backtick escapes.) | |
if($EscapedPath.Contains(' ')){ | |
# Note: [string] = [object] = [string] ... prevent arg splitting when [object] undergoes string transformation. | |
# Native utils don't need quotes (piped values/content or used as a variable/nameref), but others do. | |
# Explicit double quotes are mostly ignored, particularly cmd.exe and others strip them. | |
# Explicit single quotes are interpretted literally as if the [string] contains them, which can cause issues. | |
# ...This also simplifies copy/pasting output from console too. | |
$EscapedPath = [string]::Concat('"', $EscapedPath, '"') # Add explicit double quotes to the string # $('"' + $EscapedPath + '"') | |
# Or single quotes $("'" + "${string}" + "'") | |
# Or backtick escapes: $string.Replace(' ','` ') | |
} | |
return $EscapedPath | |
}else{return $LiteralPath} | |
}Catch{return $LiteralPath} | |
}else{return $LiteralPath} | |
}Catch{return $LiteralPath} | |
}else{return $Path} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment