1

#PSTip Check if the path is relative or absolute

Note: This tip requires PowerShell 2.0 or above.

You may want to check if a provided file/folder path is relative or absolute and perform appropriate action based on the result. The System.IO.Path namespace provides the IsPathRooted() static method. This method will return True if the path is absolute and False if it is relative. The usage of this is quite simple.

[System.IO.Path]::IsPathRooted("../Scripts")

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

This is useful especially when we are validating function parameters. You can just use this as a part of ValidateScript attribute:

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

    #....
    # Your script logic here
}

When you use the ValidateScript attribute in the function parameters, the value of -Path is first validated to check if the path is absolute or not before running the actual function code.

Filed in: Columns, Tips and Tricks Tags: , ,

One Response to "#PSTip Check if the path is relative or absolute"

  1. Maxime Beaudry says:

    IsPathRooted is dangerous because it will return true for [System.IO.Path]::IsPathRooted(“Scripts”)

    If you want this to return “false”, you should use the following:

    split-path Scripts -IsAbsolute

Leave a Reply

Submit Comment

© 2016 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: