PowerShell脚本工作目录(当前位置)

问题描述 投票:0回答:1

[当我从任何文件夹(例如C:\Scripts)启动PowerShell脚本时,脚本中的“当前” PowerShell文件夹始终是用户配置文件文件夹(例如c:\users\Joe)(仅使用Get-Location的脚本进行测试)

但是应该是启动脚本的文件夹...

我该如何解决?

powershell path scripting working-directory
1个回答
0
投票

在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-LocationPush-Location生效session-globally

  • 在类似Unix的平台(Linux,macOS)上,使用PowerShell Core,您现在可以选择使用shebang line创建(无扩展名)可执行shell脚本;这样的脚本在子进程中运行,因此no需要还原先前的位置(目录)。

    • 不幸的是,从PowerShell内核7.0.0-preview.4开始,在基于shebang的脚本中访问有关脚本自身调用的信息(包括$PSScriptRootbroken中,如this GitHub issue所述。
© www.soinside.com 2019 - 2024. All rights reserved.