[当我从任何文件夹(例如C:\Scripts
)启动PowerShell脚本时,脚本中的“当前” PowerShell文件夹始终是用户配置文件文件夹(例如c:\users\Joe
)(仅使用Get-Location
的脚本进行测试)
但是应该是启动脚本的文件夹...
我该如何解决?
在PowerShell v3 +中,自动变量$PSScriptRoot
包含执行脚本所在目录的完整路径。
如果您需要脚本以其自己的目录作为工作目录执行(当前位置),请使用以下方法:
# Switch to this script's directory.
Push-Location -LiteralPath $PSScriptRoot
try {
# Your script's body here.
# ...
$PWD # output the current location
}
finally {
# Restore the previous location.
Pop-Location
}
注意:
显式还原先前位置(目录)的原因是,PowerShell运行脚本(.ps1
文件)in-process,并且任何正在执行的脚本都会使用Set-Location
或Push-Location
生效session-globally。
在类似Unix的平台(Linux,macOS)上,使用PowerShell Core,您现在可以选择使用shebang line创建(无扩展名)可执行shell脚本;这样的脚本在子进程中运行,因此no需要还原先前的位置(目录)。
$PSScriptRoot
在broken中,如this GitHub issue所述。