powershell - 获取 powershell 脚本的位置,可选择通过符号链接
问题描述
对于“如何在 Powershell 中获取脚本本身的路径?”这个问题,很多人都提出了各种不同的答案。但是,在我的情况下,我有一些实用程序函数存储在脚本旁边的公共模块中,但我实际上并没有从该特定目录运行脚本,而是将脚本符号链接到 $HOME\bin,我有在路径中。而且我不想将所有实用程序库符号链接到 $HOME\bin 目录。
鉴于用户实际运行的脚本(即在 PATH 中找到)可以是符号链接,我如何在 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
推荐阅读
- twig - 我无法修改树枝文件
- kubernetes - Rabbitmq 节点在 kube 集群中重启
- multithreading - 使用 flutter_local_notification 创建多个 Flutter 通知
- c - 将 32 位数字插入数组时出现问题
- php - 我无法将新用户存储在部署在 herou 上的应用程序上
- numpy - return_counts=True 不返回正确的计数
- javascript - 在 Node.js 中使用画布的 marge-images
- python - 无法导入 Django:您确定它已在您的 PYTHONPATH 中安装并激活吗
- linux - systemd 无法执行带有预期参数的命令
- javascript - 移动浏览器上的服务工作者 JavaScript 问题