Quick PowerShell Tip: Check if a given path is absolute or relative

by ravikanthchaganti on July 1, 2010
160 Views

You may, sometimes, want to check if a user provided file/folder path is relative or absolute and run the appropriate action based on the result. The System.IO.Path name space provides a simple method to verify that. That method is IsPathRooted(). This method will return True if the path is absolute and False if it is relative. The usage of this is quite simple.

#This uses System.IO.Path namespace
[System.IO.Path]::IsPathRooted("../Scripts")

This will result in $false as the path we provided is relative path.

This is useful especially when we are validating parameters to a function. You can just use this as a part of ValidateScript. For example,

function Test-Path1 {
    Param (
        [Parameter(Mandatory=$True)]
        [ValidateScript({[System.IO.Path]::IsPathRooted($_)})]
        [String]$folderPath
    )            

    Write-Host $folderPath
}

Test-Path1 will validate the parameter and continues only if the value of the parameter is absolute path.

Related Posts

{ 1 trackback }

Leave a Comment

Previous post:

Next post: