首页 > 解决方案 > 以编程方式获取 powershell 中二进制文件的完整路径(其中,在哪里,Get-Command)

问题描述

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

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 中给定二进制文件的完整路径,将其存储到变量中并执行它?

标签: windowspowershellpath

解决方案


对于 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 ...

推荐阅读