PowerShell equivalent to the Unix `which` command?

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.

7 Answers

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.

0

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
3

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.

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

Try this: get-command [your command]

Get-Command doesn't find .lnk or other types, just executable commands.

To search $env:path for any file (incl. .lnk) use

@(where.exe <file pattern> 2>$null)[0]

Returns empty string if nothing found, else full path of first encounter.

Some great answers on this thread but I have found Powershell Alias's are a bit of a pain to re-define and functions are easier to write so I put this in my Powershell profile:

function global:which ([string]$command) { if (-not($command)) { throw "ERROR: Please supply a command name" } (Get-Command $command).Path
}

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like