相当于 PowerShell 中的 *Nix 'which' 命令?

问题描述 投票:0回答:18

如何询问 PowerShell 某物在哪里?

例如“which notepad”,它会根据当前路径返回运行notepad.exe的目录。

unix powershell command
18个回答
506
投票

开始在 PowerShell 中自定义个人资料后,我创建的第一个别名是“which”。

New-Alias which get-command

要将其添加到您的个人资料中,请输入以下内容:

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

最后一行开头的 `n 是为了确保它将作为新行开始。


203
投票

这是一个实际的 *nix 等效项,即它提供 *nix 风格的输出。

Get-Command <your command> | Select-Object -ExpandProperty Definition

只需替换为您要查找的任何内容即可。

PS C:\> Get-Command notepad.exe | Select-Object -ExpandProperty Definition
C:\Windows\system32\notepad.exe

当您将其添加到您的配置文件时,您将需要使用函数而不是别名,因为您不能在管道中使用别名:

function which($name)
{
    Get-Command $name | Select-Object -ExpandProperty Definition
}

现在,当您重新加载个人资料时,您可以执行以下操作:

PS C:\> which notepad
C:\Windows\system32\notepad.exe

117
投票

我通常只是输入:

gcm notepad

gcm note*

gcm 是 Get-Command 的默认别名。

在我的系统上,gcm note* 输出:

[27] » gcm note*

CommandType     Name                                                     Definition
-----------     ----                                                     ----------
Application     notepad.exe                                              C:\WINDOWS\notepad.exe
Application     notepad.exe                                              C:\WINDOWS\system32\notepad.exe
Application     Notepad2.exe                                             C:\Utils\Notepad2.exe
Application     Notepad2.ini                                             C:\Utils\Notepad2.ini

您将获得与您要查找的内容相匹配的目录和命令。


45
投票

尝试这个例子:

(Get-Command notepad.exe).Path

12
投票

我对 Which 函数的建议:

function which($cmd) { get-command $cmd | % { $_.Path } }

PS C:\> which devcon

C:\local\code\bin\devcon.exe

10
投票

与 Unix 的快速而肮脏的匹配

which

New-Alias which where.exe

但是它会返回多行(如果存在),那么它就变成了

function which {where.exe command | select -first 1}

7
投票

我喜欢

Get-Command | Format-List
,或更短,为两者使用别名,并且仅用于
powershell.exe
:

gcm powershell | fl

您可以这样查找别名:

alias -definition Format-List

制表符补全与

gcm
配合使用。

要让选项卡立即列出所有选项:

set-psreadlineoption -editmode emacs

3
投票

这似乎可以满足您的要求(我在 http://huddledmasses.org/powershell-find-path/ 上找到了它):

Function Find-Path($Path, [switch]$All = $false, [Microsoft.PowerShell.Commands.TestPathType]$type = "Any")
## You could comment out the function stuff and use it as a script instead, with this line:
#param($Path, [switch]$All = $false, [Microsoft.PowerShell.Commands.TestPathType]$type = "Any")
   if($(Test-Path $Path -Type $type)) {
      return $path
   } else {
      [string[]]$paths = @($pwd);
      $paths += "$pwd;$env:path".split(";")

      $paths = Join-Path $paths $(Split-Path $Path -leaf) | ? { Test-Path $_ -Type $type }
      if($paths.Length -gt 0) {
         if($All) {
            return $paths;
         } else {
            return $paths[0]
         }
      }
   }
   throw "Couldn't find a matching path of type $type"
}
Set-Alias find Find-Path

3
投票

检查这个 PowerShell Which

那里提供的代码表明了这一点:

($Env:Path).Split(";") | Get-ChildItem -filter notepad.exe

2
投票

在 Windows 2003 或更高版本(或者 Windows 2000/XP,如果您安装了资源工具包)上尝试使用

where
命令。

顺便说一句,这在其他问题中得到了更多答案:

Windows 上有相当于“which”的吗?

PowerShell 相当于 Unix

which
命令?


2
投票

如果您想要一个既接受来自管道的输入或作为参数的comamnd,您应该尝试以下操作:

function which($name) {
    if ($name) { $input = $name }
    Get-Command $input | Select-Object -ExpandProperty Path
}

将命令复制粘贴到您的个人资料中 (

notepad $profile
)。

示例:

❯ echo clang.exe | which
C:\Program Files\LLVM\bin\clang.exe

❯ which clang.exe
C:\Program Files\LLVM\bin\clang.exe

1
投票

我的 PowerShell 配置文件中有这个

which
高级功能:

    function which {
    <#
    .SYNOPSIS
    Identifies the source of a PowerShell command.
    .DESCRIPTION
    Identifies the source of a PowerShell command. External commands (Applications) are identified by the path to the executable
    (which must be in the system PATH); cmdlets and functions are identified as such and the name of the module they are defined in
    provided; aliases are expanded and the source of the alias definition is returned.
    .INPUTS
    No inputs; you cannot pipe data to this function.
    .OUTPUTS
    .PARAMETER Name
    The name of the command to be identified.
    .EXAMPLE
    PS C:\Users\Smith\Documents> which Get-Command
    
    Get-Command: Cmdlet in module Microsoft.PowerShell.Core
    
    (Identifies type and source of command)
    .EXAMPLE
    PS C:\Users\Smith\Documents> which notepad
    
    C:\WINDOWS\SYSTEM32\notepad.exe
    
    (Indicates the full path of the executable)
    #>
        param(
        [String]$name
        )
    
        $cmd = Get-Command $name
        $redirect = $null
        switch ($cmd.CommandType) {
            "Alias"          { "{0}: Alias for ({1})" -f $cmd.Name, (. { which $cmd.Definition } ) }
            "Application"    { $cmd.Source }
            "Cmdlet"         { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }
            "Function"       { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }
            "Workflow"       { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }
            "ExternalScript" { $cmd.Source }
            default          { $cmd }
        }
    }

0
投票

用途:

function Which([string] $cmd) {
  $path = (($Env:Path).Split(";") | Select -uniq | Where { $_.Length } | Where { Test-Path $_ } | Get-ChildItem -filter $cmd).FullName
  if ($path) { $path.ToString() }
}

# Check if Chocolatey is installed
if (Which('cinst.bat')) {
  Write-Host "yes"
} else {
  Write-Host "no"
}

或者这个版本,调用原来的where命令。

这个版本也效果更好,因为它不限于bat文件:

function which([string] $cmd) {
  $where = iex $(Join-Path $env:SystemRoot "System32\where.exe $cmd 2>&1")
  $first = $($where -split '[\r\n]')
  if ($first.getType().BaseType.Name -eq 'Array') {
    $first = $first[0]
  }
  if (Test-Path $first) {
    $first
  }
}

# Check if Curl is installed
if (which('curl')) {
  echo 'yes'
} else {
  echo 'no'
}

0
投票

您可以从

https://goprogram.co.uk/software/commands
安装 which 命令以及所有其他 UNIX 命令。


0
投票

如果您有 scoop,您可以安装其直接克隆:

scoop install which
which notepad

0
投票

始终可以选择使用哪个。实际上有三种方法可以从 Windows powershell 访问 which,第一种(不一定是最好的)wsl -e which 命令(这需要安装适用于 Linux 的 Windows 子系统和正在运行的发行版)。 B. gnuwin32,它是几个 .exe 格式的 gnu 二进制文件的端口,作为独立的捆绑 lanunchers 选项三,安装 msys2(跨编译器平台),如果你去它安装在 /usr/bin 的地方,你会发现很多许多更新的 gnu 实用程序。它们中的大多数都作为独立的 exe 工作,可以从 bin 文件夹复制到您的主驱动器某处并添加到您的 PATH 中。


0
投票

最好将

where.exe
包装到函数中,以便它以二进制作为命令行参数并将函数放入
$PROFILE
中。另外,最好使用
where.exe
而不是
(Get-Command $binary).Source
方法。

为什么?让我们考虑一下

(Get-Command $binary).Source
,其中
$binary
与已在
$PROFILE
中编写的别名匹配,例如
New-Alias curl C:\curl-7.81.0-win64-mingw\bin\curl.exe
(因为您想使用自己安装的curl,而不是 system32 中的curl)。那么
(Get-Command curl).Source
将不会输出任何内容。而且,即使
(Get-Command curl.exe).Source
也只会输出system32的路径:

C:\Windows\System32\curl.exe

但是

where.exe curl
输出看起来像这样:

C:\Windows\System32\curl.exe
C:\curl-7.81.0-win64-mingw\bin\curl.exe

因此,将代码添加到

$PROFILE

function Find-Binary($binary) {
    $location = where.exe $binary 2>$null
    Write-Output $location
}

New-Alias wi Find-Binary

wi
whereis

的缩写

然后像这样使用它:

wi your_binary

Find-Binary your_binary

-1
投票

始终可以选择使用哪个。实际上有三种方法可以从 Windows powershell 访问它

  • 第一个(虽然不是最好的)是 wsl(适用于 Linux 的 Windows 子系统)
wsl -e which command 

这需要安装适用于 Linux 的 Windows 子系统和正在运行的发行版。

  • 接下来是gnuwin32,它是几个 .exe 格式的 gnu 二进制文件的端口,作为独立的捆绑 lanunchers

  • 第三,安装msys2(交叉编译器平台),如果你去/usr/bin中安装它的地方,你会发现很多很多更新的gnu utils。它们中的大多数都作为独立的 exe 工作,可以从 bin 文件夹复制到您的主驱动器某处并添加到您的 PATH 中。

© www.soinside.com 2019 - 2024. All rights reserved.