PowerShell equivalent to the Unix `which` command?

76

19

Does PowerShell have an equivalent to the which command found in most (if not all) Unix shells?

There are a number of times I'd like to know the location of something I'm running from the command line. In Unix I just do which <command>, and it tells me. I can't find an equivalent in PowerShell.

Herms

Posted 2009-09-02T18:55:42.960

Reputation: 7 644

Answers

78

This was asked and answered on Stack Overflow: Equivalent of *Nix 'which' command in PowerShell?

The very first alias I made once I started customizing my profile in PowerShell was 'which'.

New-Alias which get-command

To add this to your profile, type this:

"`nNew-Alias which get-command" | add-content $profile

The `n at the start of the last line is to ensure it will start as a new line.

user4358

Posted 2009-09-02T18:55:42.960

Reputation:

39

As of PowerShell 3.0, you can do

(Get-Command cmd).Path

Which also has the benefit over vanilla Get-Command of returning a System.String so you get a clean *nixy single line output like you may be used to. Using the gcm alias, we can take it down to 11 characters.

(gcm cmd).Path

FLGMwt

Posted 2009-09-02T18:55:42.960

Reputation: 491

1This should be the accepted answer as it actually tells you what is the Powershell equivalent of the *NIX command where rather than teaching you how to set aliases on Powershell, which is not the title of the question. – mastazi – 2015-07-12T23:31:52.830

3@mastazi: But that fails for builtins, which is a regression compared to e.g. zsh's which. (where, by the way, is actually a Windows utility that can do a number of different things, one of which roughly approximates searching for a command along the PATH.) Also, there's nothing wrong with an answer that explains how to do what was asked and also another, slightly more involved thing built on that. – SamB – 2017-11-29T23:04:45.760

4If Get-Command finds multiple results, it returns an array. Additionally, if the command it finds is not an executable, Path is undefined ($null). This makes the answer here impractical for general use without heavy modification. For a good example of both these cases, try Get-Command where. – jpmc26 – 2014-05-30T17:14:59.547

7

Also answered in 2008: Is there an equivalent of 'which' on the Windows command line?

Try the where command if you've installed a Resource Kit.

Most important parts of the answer:

Windows Server 2003 and later provide the WHERE command which does some of what which does, though it matches all types of files, not just executable commands.

[snip]

In Windows PowerShell you must type where.exe.

Anonymous

Posted 2009-09-02T18:55:42.960

Reputation: 81

3

function which([string]$cmd) {gcm -ErrorAction "SilentlyContinue" $cmd | ft Definition}

hshen

Posted 2009-09-02T18:55:42.960

Reputation: 39