Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the file system location of a PowerShell script?

I have a PowerShell script located at D:\temp.

When I run this script, I want the current location of the file to be listed. How do I do this?

For example, this code would accomplish it in a DOS batch file; I am trying to convert this to a PowerShell script...

FOR /f "usebackq tokens=*" %%a IN ('%0') DO SET this_cmds_dir=%%~dpa CD /d "%this_cmds_dir%" 
like image 263
Santhosh Avatar asked Sep 08 '10 11:09

Santhosh


People also ask

How do I find the location of a PowerShell script?

To get the full path of the script we need to use the $myInvocation command. This is an automatic variable and it is only invoked when the script or the function is executed. $MyInvocation.

How do you get the full path of ChildItem?

Use the Get-ChildItem cmdlet in PowerShell to get the files in the folder using the file filter and using the Select-Object cmdlet to get the full path of the file using ExpandProperty FullName.

How do I navigate to a file path in PowerShell?

Using command-line utilities The Windows PowerShell prompt opens by default at the root of your user folder. Change to the root of C:\ by entering cd c:\ inside the Windows PowerShell prompt.

How do I get the path environment variable in PowerShell?

Environment variables in PowerShell are stored as PS drive (Env: ). To retrieve all the environment variables stored in the OS you can use the below command. You can also use dir env: command to retrieve all environment variables and values.


1 Answers

PowerShell 3+

The path of a running scripts is:

$PSCommandPath 

Its directory is:

$PSScriptRoot 

PowerShell 2

The path of a running scripts is:

$MyInvocation.MyCommand.Path 

Its directory is:

$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent 
like image 97
Roman Kuzmin Avatar answered Sep 22 '22 22:09

Roman Kuzmin