This time it’s a very simple trick, but a very useful one when I have a script that receives a path as a parameter. It’s very typical not to know whether the path is absolute or relative, and very common to want to do a Join-Path with the current path (or any other) when the path is relative.

Sometimes I forget that PowerShell has all the power of .Net at its disposal, and in this case that’s exactly what’s useful. Using the IsPathRooted method of System.IO.Path I can find out whether the path is absolute or relative and act accordingly. This would be a typical example of these cases.

param([string]$Path)

$targetPath = pwd

if (-not [string]::IsNullOrWhiteSpace($Path)) {
	if ([System.IO.Path]::IsPathRooted($Path)) {
		$targetPath = $Path
	} else{
		$targetPath = Join-Path (pwd) $Path
	}
}

As a bonus, this script comes with another example where turning to .Net is very handy: the IsNullOrWhiteSpace() method.