This article describes how to get the directory where the script file (. ps1 file) is located in the PowerShell script. This article describes the method applied to PowerShell 3.0.
In PowerShell 3.0, there is a variable that makes it easy to get the directory where the script resides. We are in E:\ps\script1.ps1 and SCRIPT2.PS1, the contents are as follows:
SCRIPT1.PS1 content:
Copy Code code as follows:
Write-host "This is Script1.ps1"
Write-host "Let me call Script2.ps1:"
. "$PSScriptRoot \script2.ps1"
SCRIPT2.PS1 content:
Copy Code code as follows:
Write-host "This is Script2.ps1"
Running SCRIPT1.PS1 will use the script code that invokes Script2.ps1.
Note that in the Script1.ps1 script, we use the $psscriptroot variable to get the directory where the script resides. This variable is a new addition to the variable in PowerShell 3.0. When running the Script1.ps1 script, this variable refers to the E:\ps directory path.
OK, about PowerShell use $psscriptroot to get the directory where the script is located, this article introduces so much, hope to be helpful to everybody.