Michael Altfield
Michael Altfield

Reputation: 2777

Programatically get full path to binary in powershell (which, where, Get-Command)

How do I get the absolute path to a given binary and store it to a variable?

What is the equivalent to the following for Linux Bash in Windows Powershell?

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

In Windows Powershell, there's Get-Command, but the output is hardly trivial to parse programmatically for a script.

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>

How can I programmatically determine the full path to a given binary in Windows Powershell, store it to a variable, and execute it?

Upvotes: 3

Views: 2115

Answers (1)

Michael Altfield
Michael Altfield

Reputation: 2777

For the example command provided by the OP question:

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>

You can extract the "Source" field with the following syntax

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

Then you can also store it to a variable and execute it with an ampersand (&) preceding the variable

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

Upvotes: 4

Related Questions