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%"
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With