PowerShell执行which命令报错:‘which’未被识别为有效命令,如何解决?
Hey there! I’ve dealt with this exact frustration before—PowerShell doesn’t come with the which command built-in like Unix-based shells (Bash, Zsh, etc.) do. No worries though, there are a few easy ways to get the same functionality:
Use PowerShell’s native
Get-Command(or its aliasgcm)
This is the official PowerShell replacement forwhich. To find the path of a command, run:Get-Command xxxxxxOr use the shorter alias for quicker typing:
gcm xxxxxxIf you only want to see the raw executable file path (and skip extra metadata), pipe the output to narrow it down:
gcm xxxxxx | Select-Object -ExpandProperty SourceYou can also filter results to only show applications (ignoring scripts or aliases) with:
gcm xxxxxx -CommandType ApplicationCreate a custom
whichfunction (to keep using the familiar syntax)
If you’d rather stick with typingwhichlike you do in Unix shells, you can add a simple function to your PowerShell profile. Here’s how:- Open your PowerShell profile file with:
(If the file doesn’t exist, runnotepad $PROFILENew-Item -Path $PROFILE -ItemType Filefirst to create it.) - Paste this function into the file:
function which { Get-Command -Name $args[0] -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source } - Save the file, then restart PowerShell or run
. $PROFILEto load the changes right away. Now you can runwhich xxxxxxjust like you’re used to!
- Open your PowerShell profile file with:
Use Windows’ built-in
where.exe
Windows has its own native tool for locating executable files, which works almost exactly likewhich. Run:where.exe xxxxxxThis will return the full path of any matching executable in your system’s
PATHvariable.
The root cause of that error is straightforward: which isn’t a native PowerShell cmdlet—it’s exclusive to Unix-like environments. All the options above give you the same (or better) functionality directly in PowerShell.
内容的提问来源于stack exchange,提问作者wtian

