How to Get the File System Location of a PowerShell Script

Rohan Timalsina Feb 02, 2024
  1. Use $PSCommandPath to Get the File System Location of a PowerShell Script
  2. Use $PSScriptRoot to Get the File System Location of a PowerShell Script
  3. Use $MyInvocation to Get the File System Location of a PowerShell Script
How to Get the File System Location of a PowerShell Script

The location of a file is indicated by a file path. There are multiple methods to get the full path of a file using PowerShell.

Is it possible to find the location of a PowerShell script currently running? The answer is yes.

This tutorial will introduce different methods to get the file system location of a PowerShell script that is being executed.

Use $PSCommandPath to Get the File System Location of a PowerShell Script

$PSCommandPath is one of the automatic variables in PowerShell. Automatic variables are created and maintained by PowerShell.

$PSCommandPath stores the full path of the script that is being run. It is valid in all PowerShell scripts.

For example, you can include the variable $PSCommandPath in your script to get the location of a running script in PowerShell.

Write-Host "Path of the script: $PSCommandPath"

Run the script.

.\myscript1.ps1

Output:

Path of the script: C:\Users\rhntm\myscript1.ps1

Use $PSScriptRoot to Get the File System Location of a PowerShell Script

$PSScriptRoot stores the full path of the running script’s parent directory. You can use the $PSScriptRoot variable to get the directory where a script file is located.

For example:

Write-Host "Script's directory: $PSScriptRoot"

Run the script.

.\myscript2.ps1

Output:

Script's directory: C:\Users\rhntm

It is valid in all scripts from PowerShell 3.0.

Use $MyInvocation to Get the File System Location of a PowerShell Script

The automatic variable $MyInvocation contains information of the current command, such as its name, parameters, and parameter values. You can include the $MyInvocation.MyCommand.Path in a script file to get the full path of a running script in PowerShell.

Write-Host "Path:"
$MyInvocation.MyCommand.Path

Run the script.

.\myscript3.ps1

Output:

Path:
C:\Users\rhntm\myscript3.ps1

We hope that this tutorial helps you learn how to get the file system location of a running PowerShell script.

Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell Script