如何获取我执行的PowerShell脚本的目录?

use*_*116 48 powershell

我运行PowerShell脚本.如何获取我运行的此脚本的目录路径?

这该怎么做?

Aar*_*sen 137

PowerShell 3具有$PSScriptRoot 自动变量:

包含运行脚本的目录.

在Windows PowerShell 2.0中,此变量仅在脚本模块(.psm1)中有效.从Windows PowerShell 3.0开始,它在所有脚本中都有效.

不要被糟糕的措辞所迷惑.PSScriptRoot是当前文件的目录.

在PowerShell 2中,您可以计算$PSScriptRoot自己的价值:

# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
Run Code Online (Sandbox Code Playgroud)

  • 为什么投票失败?帮助我更好地回答我的问题.请提供反馈! (13认同)
  • @monojohnny $ MyInvocation在控制台中不可用,仅在函数和脚本中可用。 (3认同)
  • 我对powershell有点新意,你能扩展一下$ MyInvocation.MyCommand.Definition吗?我在很多帖子中看到这个,它看起来像一个占位符,但为了什么? (2认同)