以程式設計方式取得 powershell 中二進位檔案的完整路徑(which、where、Get-Command)

以程式設計方式取得 powershell 中二進位檔案的完整路徑(which、where、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 中給定二進位檔案的完整路徑、將其儲存到變數並執行它?

答案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 ...

相關內容