Odpowiednik polecenia * Nix 'which' W PowerShell?

Jak zapytać PowerShell gdzie coś jest?

Na przykład, "który notatnik" i zwraca katalog, w którym notatnik.exe jest uruchamiany zgodnie z bieżącymi ścieżkami.

Author: Peter Mortensen, 2008-09-15

14 answers

Pierwszym aliasem, który stworzyłem, gdy zacząłem dostosowywać swój profil w PowerShell, było 'which'.

New-Alias which get-command

Aby dodać to do swojego profilu, wpisz to:

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

`n na początku ostatniej linii ma zapewnić, że zacznie się jako nowa linia.

 438
Author: halr9000,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-09 07:49:55

Tutaj jest rzeczywisty odpowiednik * nix, tzn. daje wyjście w stylu * nix.

Get-Command <your command> | Select-Object -ExpandProperty Definition
Po prostu zastąp to, czego szukasz.
PS C:\> Get-Command notepad.exe | Select-Object -ExpandProperty Definition
C:\Windows\system32\notepad.exe

Kiedy dodasz go do swojego profilu, będziesz chciał użyć funkcji, a nie aliasu, ponieważ nie możesz używać aliasów z rurami:

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

Teraz, gdy przeładujesz swój profil, możesz to zrobić:

PS C:\> which notepad
C:\Windows\system32\notepad.exe
 181
Author: petrsnd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-05 20:22:09

Zwykle wpisuję:

gcm notepad

Lub

gcm note*

Gcm jest domyślnym aliasem polecenia Get.

W moim systemie, GCM note* wyjścia:

[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

Otrzymujesz katalog i polecenie, które pasuje do tego, czego szukasz.

 92
Author: David Mohundro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-15 15:22:32

Wypróbuj ten przykład:

(Get-Command notepad.exe).Path
 42
Author: thesqldev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-01 04:39:09

Moja propozycja dla funkcji która:

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

PS C:\> which devcon

C:\local\code\bin\devcon.exe
 8
Author: VortiFred,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-09 08:10:09

Szybkie i brudne dopasowanie do Uniksa which to

New-Alias which where.exe

Ale zwraca wiele linii, jeśli istnieją, więc staje się

function which {where.exe command | select -first 1}
 6
Author: Chris F Carroll,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-01 09:58:00

To chyba robi co chcesz (znalazłem to na 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
Author: Nicholas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-09 07:53:02

Sprawdź to PowerShell który .

Podany tam kod sugeruje to:

($Env:Path).Split(";") | Get-ChildItem -filter notepad.exe
 3
Author: tzot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-09 07:55:20

Lubię Get-Command | Format-List, lub krócej, używając aliasów dla dwóch i tylko dla powershell.exe:

gcm powershell | fl

Możesz znaleźć takie aliasy:

alias -definition Format-List

Uzupełnianie kart działa z gcm.

 3
Author: js2010,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-09 08:34:35

Spróbuj where polecenie w systemie Windows 2003 lub nowszym (lub Windows 2000 / XP, jeśli zainstalowano zestaw zasobów).

BTW, to dostało więcej odpowiedzi w innych pytaniach:

Czy w systemie Windows istnieje odpowiednik 'który'?

PowerShell odpowiednik polecenia Unix which?

 2
Author: Anonymous,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-09 08:08:08

Użycie:

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"
}

Lub tej wersji, wywołując oryginalną komendę where.

Ta wersja działa również lepiej, ponieważ nie ogranicza się do plików 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
Author: Jerome,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-09 08:09:22

Jeśli chcesz, aby komamnd przyjmował dane wejściowe z pipeline lub jako parametr, powinieneś spróbować tego:

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

Skopiuj-wklej polecenie do swojego profilu (notepad $profile).

Przykłady:

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

❯ which clang.exe
C:\Program Files\LLVM\bin\clang.exe
 0
Author: Amin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-01 07:36:04

Możesz zainstalować which polecenie z https://goprogram.co.uk/software/commands , wraz ze wszystkimi innymi poleceniami Uniksa.

 0
Author: George Ogden,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-20 12:50:12

Mam tę which zaawansowaną funkcję w moim profilu PowerShell:

    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
Author: Jeff Zeitlin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-30 14:25:09