首页 > 解决方案 > 获取 powershell 脚本的位置,可选择通过符号链接

问题描述

对于“如何在 Powershell 中获取脚本本身的路径?”这个问题,很多人都提出了各种不同的答案。但是,在我的情况下,我有一些实用程序函数存储在脚本旁边的公共模块中,但我实际上并没有从该特定目录运行脚本,而是将脚本符号链接到 $HOME\bin,我有在路径中。而且我不想将所有实用程序库符号链接到 $HOME\bin 目录。

鉴于用户实际运行的脚本(即在 PATH 中找到)可以是符号链接,我如何在 Powershell 中获取“真实”脚本路径的路径?

标签: powershell

解决方案


这有点笨拙,但使用 common$PSCommandPath获取脚本路径名,然后尝试查找它链接到的内容。如果没有结果,那$PSCommandPath就是答案。否则检查它是否是绝对链接目标路径;如果是,那就是答案。否则将符号链接的路径与其目标连接起来。最后Resolve-Path用于“删除”合并路径名的相对部分。

Function Get-RealScriptPath() {
  # Get script path and name
  $ScriptPath = $PSCommandPath

  # Attempt to extract link target from script pathname
  $link_target = Get-Item $ScriptPath | Select-Object -ExpandProperty Target

  # If it's not a link ..
  If(-Not($link_target)) {
    # .. then the script path is the answer.
    return $ScriptPath
  }

  # If the link target is absolute ..
  $is_absolute = [System.IO.Path]::IsPathRooted($link_target)
  if($is_absolute) {
    # .. then it is the answer.
    return $link_target
  }

  # At this point:
  # - we know that script was launched from a link
  # - the link target is probably relative (depending on how accurate
  #   IsPathRooted() is).
  # Try to make an absolute path by merging the script directory and the link
  # target and then normalize it through Resolve-Path.
  $joined = Join-Path $PSScriptRoot $link_target
  $resolved = Resolve-Path -Path $joined
  return $resolved
}

Function Get-ScriptDirectory() {
  $ScriptPath = Get-RealScriptPath
  $ScriptDir = Split-Path -Parent $ScriptPath
  return $ScriptDir
}

$ScriptDir = Get-ScriptDirectory

推荐阅读