如何获取给定二进制文件的绝对路径并将其存储到变量中?
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 中给定二进制文件的完整路径,将其存储到变量中并执行它?
答案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 ...