【问题标题】:Programatically get full path to binary in powershell (which, where, Get-Command)以编程方式获取 powershell 中二进制文件的完整路径(其中,在哪里,Get-Command)
【发布时间】:2021-11-18 20:01:01
【问题描述】:

如何获取给定二进制文件的绝对路径并将其存储到变量中?

Windows Powershell 中的 Linux Bash 与以下等效项是什么?

user@disp985:~$ path=`which gpg`
user@disp985:~$ echo $path
/usr/bin/gpg
user@disp985:~$ 

user@disp985:~$ $path
gpg: keybox '/home/user/.gnupg/pubring.kbx' created
gpg: WARNING: no command supplied.  Trying to guess what you mean ...
gpg: Go ahead and type your message ...

在 Windows Powershell 中,有 Get-Command,但输出很难以编程方式解析脚本。

PS C:\Users\user> Get-Command gpg.exe
 
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Application     gpg.exe                                            2.2.28.... C:\Program Files (x86)\Gpg4win\..\GnuP...
 
 
PS C:\Users\user>

如何以编程方式确定 Windows Powershell 中给定二进制文件的完整路径,将其存储到变量中并执行它?

【问题讨论】:

标签: windows powershell path


【解决方案1】:

对于OP问题提供的示例命令:

PS C:\Users\user> Get-Command gpg.exe
 
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Application     gpg.exe                                            2.2.28.... C:\Program Files (x86)\Gpg4win\..\GnuP...
 
 
PS C:\Users\user>

您可以使用以下语法提取“来源”字段

PS C:\Users\user> $(Get-Command gpg.exe).Source
C:\Program Files (x86)\Gpg4win\..\GnuPG\bin\gpg.exe

然后你也可以将它存储到一个变量中,并在变量前加上一个&符号来执行它

PS C:\Users\user> $path=$(Get-Command gpg.exe).Source
PS C:\Users\user> echo $path
C:\Program Files (x86)\Gpg4win\..\GnuPG\bin\gpg.exe
PS C:\Users\user> & $path
gpg: WARNING: no command supplied.  Trying to guess what you mean ...
gpg: Go ahead and type your message ...

【讨论】:

  • 如果Get-Command 能够为gpg.exe 提供绝对路径,那么您实际上不需要它。您可以直接使用& gpg.exegpg 直接调用它。
  • 这个问题是有意将which 用法映射到等效的powershell。但是,这在 bash 中是个坏主意,因为用户可能会使用别名覆盖 gpg,这可能会从脚本中产生不确定的结果。在 powershell 中,我的用例是执行一个存在于 Windows 上许多不同位置的二进制文件。如果可能,我想使用特定路径。然后在需要和可能的情况下求助于其他人。
  • 很好,但请注意,$(...) 仅在两种情况下才需要:(a) 将整个 语句,特别是循环和条件语句,嵌入到另一个语句中, 和 (b) 将表达式、命令或语句嵌入到 "..." 中,这是一个可扩展(插值)字符串。只需 (...) 就足以在语句中嵌入单个 commandexpression (即使在 variable assignment 的 RHS 上也不需要这样做我>)。虽然不太可能,但不必要地使用 $(...) 可能会产生副作用 - 请参阅 this answer
猜你喜欢
  • 1970-01-01
  • 2012-10-19
  • 2019-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多