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 which needs to be executed. So How do you Determine the Location of the Current PowerShell script?

For an 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. 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.

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

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

 

You may also like...

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.