Get the path relative to the script location - Powershell

If you're working with separate files in Powershell, chances are you need to refer to their file path.

However, if you use the absolute path, there is a good chance the script will fail when it is executed on a different machine.

Unless of course, the directory structure is identical, or you're importing/exporting a file with a well established location (i.e. system32/drivers/etc/hosts on Windows).

If the file will always be in a location relative to the script (i.e. in the same folder), we want to use the relative path.

Fortunately, we can do so using $PSScriptRoot.

Executing without a path

Let's first look at an example without $PSScriptRoot.

If I use Get-ChildItem by itself in a script in the folder C:\Users\Sean\Documents\Scripts, I get:

Get-ChildItem
    Directory: C:\Users\Sean


Mode                 LastWriteTime         Length Name                               
----                 -------------         ------ ----                               
d-----        25/01/2021     16:25                .android                           
d-----        03/07/2020     21:00                .AndroidStudio4.0                  
d-----        26/07/2019     21:32                .config                            
d-----        15/07/2020     11:40                .dbus-keyrings                     
d-----        21/02/2021     13:24                .docker    

...etc

Instead of running the command in the current directory, it has listed the contents of the operating system user's root directory.

Getting the relative path

And if I use $PSScriptRoot:

Get-ChildItem $PSScriptRoot
    Directory: C:\Users\Sean\Documents\Scripts


Mode                 LastWriteTime         Length Name                               
----                 -------------         ------ ----                               
d-----        06/04/2021     12:32                MyFolder       

You can also use it as part of the path:

Get-ChildItem $PSScriptRoot\MyFolder
    Directory: C:\Users\Sean\Documents\Scripts\MyFolder


Mode                 LastWriteTime         Length Name                               
----                 -------------         ------ ----                               
-a----        06/04/2021     12:32              0 MyFile.txt