$PSScriptRoot automatic variable in PowerShell Contains the full path to the script that uses $PSScriptRoot variable in the script or command. $PSScriptRoot is one of the automatic variables which is read-only and its values are assigned when the caller is a script.
In this article, I will explain about $PSScriptRoot automatic variable in PowerShell and its information.
PowerShell PSScriptRoot Empty
PowerShell PSScriptRoot is empty if it is used outside of PowerShell script or caller is not script or command.
Let’s understand PowerShell $PSScriptRoot empty with below command
PS D:\PowerShell> $PSScriptRoot PS D:\PowerShell>
In the above script, as PSScriptRoot is not invoked by script or within any command, hence its value by default is empty or null.
Cool Tip: Get-ChildItem cmdlet – Search for files in PowerShell!
$PSScriptRoot variable in PowerShell
PowerShell $PSscriptRoot contains the full filesystem path of the directory from which the current script or command is being executed or run.
Let’s understand PowerShell PSScriptRoot with an example, run below command
PS D:\PowerShell> Get-ChildItem -Path $PSScriptRoot Directory: D:\PowerShell Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 24-10-2020 19:17 Excel d----- 17-07-2021 15:15 FTP-101 d----- 05-10-2020 21:14 Zip -a---- 04-10-2020 14:40 51 ActiveDirectoryGroupList.csv -a---- 24-10-2020 19:15 29 complist.txt -a---- 24-10-2020 20:08 118 comppingstatus.csv -a---- 04-10-2020 12:29 8579 Employee.xlsx -a---- 03-07-2021 17:01 961 print-spooler-service.ps1 -a---- 05-10-2020 21:01 2775006 vscode-docker-master.zip
In the above PowerShell Get-ChildItem command, the $PSScriptRoot variable is used within the command. It gets the full path of the executing script parent directory.
In PowerShell 2.0 version, the PowerShell PSScriptRoot variable is valid only in script modules (.psm1). It’s now valid in all scripts.
Cool Tip: To get memory usage in PowerShell!
PowerShell PSScriptRoot automatic variable contains the information about the directory in which the script is being executed and its value assigned if it is used within script or command.
There are other automatic variables like $Error in PowerShell which contains error information if raised in script execution.
You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.