-1

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?

Michael Altfield
  • 739
  • 2
  • 8
  • 23
  • 2
    `hardly trivial to parse`? PowerShell is object oriented, there is no need to parse anything. It's not going to get more trivial. – Gerald Schneider Sep 26 '21 at 05:21
  • 1
    Apart from that, the question is off topic, programming questions belong on [so]. Chances are high that this question was already answered there. – Gerald Schneider Sep 26 '21 at 05:23
  • I agree it's off topic on server fault – djdomi Sep 26 '21 at 09:07
  • not sure how typing commands into a powershell terminal is programming, seems like Server Fault to me.. – Michael Altfield Sep 26 '21 at 09:35
  • Usually it's not necessary to get an object's preferences as a (string type) variable. Just use it whereever you are. The "closest" thing to a batch (bash) string-output would be `Get-Command format | Format-List Source`, which would be fairly easy to parse. – bjoster Oct 04 '21 at 09:02

1 Answers1

1

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 ...
Michael Altfield
  • 739
  • 2
  • 8
  • 23