Determine the Location of the Current PowerShell script

If you are a PowerShell programmer the most often you would have come across this scenario where you need to call another PowerShell script or execute some batch file from the PowerShell script. In this case, you should not hard code the path of another script that needs to be executed. So How do you Determine the Location of the Current PowerShell script?

For Example, Let’s Consider we have 2 script files.

  • Scripts\example1.ps1
  • Scripts\example2.ps1

The first Script will call the second script and performs some operations. So if you just provide & .\example.ps2 it will not work. Only if you are running the script from the current directory then this might work else if you call it from the command prompt or some other directory it will throw an exception saying “CommandNotFound”.

Also if you are running the PowerShell scripts on the server then you have no idea where the Network admin might copy your PowerShell scripts and execute them. So it is always better not to hard code the paths in the Script.

Determine the Location of the Current PowerShell script

There are different commands for different PowerShell versions. We will look into all the versions.

#1. Get the Path of Current Executing Script in PowerShell Version 3.0+

You could use any of the below commands to get the current directory of the PowerShell Script.

$PSScriptRoot
function Get-ScriptDirectory {
  Split-Path -Parent $PSCommandPath
}

#2. Get the Path of Current Executing Script in PowerShell Version 2.0 and 1.0

If you are working on PowerShell version 2.0 and 1.0 then the below command is the best option to find out the script directory path.

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
Write-Host "Current ScriptPath"
$scriptPath
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like