Equivalente ao comando *Nix 'qual' no PowerShell?
-
09-06-2019 - |
Pergunta
Como pergunto ao PowerShell onde está algo?
Por exemplo, "qual bloco de notas" e retorna o diretório onde o notepad.exe é executado de acordo com os caminhos atuais.
Solução
O primeiro alias que criei quando comecei a personalizar meu perfil no PowerShell foi ‘qual’.
New-Alias which get-command
Para adicionar isso ao seu perfil, digite isto:
"`nNew-Alias which get-command" | add-content $profile
O `n no início da última linha é para garantir que ela começará como uma nova linha.
Outras dicas
Aqui está um equivalente *nix real, ou seja,fornece saída no estilo *nix.
Get-Command <your command> | Select-Object -ExpandProperty Definition
Basta substituir pelo que você procura.
PS C:\> Get-Command notepad.exe | Select-Object -ExpandProperty Definition
C:\Windows\system32\notepad.exe
Ao adicioná-lo ao seu perfil, você desejará usar uma função em vez de um alias porque não pode usar aliases com pipes:
function which($name)
{
Get-Command $name | Select-Object -ExpandProperty Definition
}
Agora, ao recarregar seu perfil, você pode fazer o seguinte:
PS C:\> which notepad
C:\Windows\system32\notepad.exe
Normalmente eu apenas digito:
gcm notepad
ou
gcm note*
gcm é o alias padrão para Get-Command.
No meu sistema, gcm note* gera:
[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
Você obtém o diretório e o comando que corresponde ao que procura.
Experimente este exemplo:
(Get-Command notepad.exe).Path
Isso parece fazer o que você quer (encontrei em 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
Verifique isso PowerShell Qual.
O código fornecido lá sugere o seguinte:
($Env:Path).Split(";") | Get-ChildItem -filter notepad.exe
Minha proposta para a função Qual:
function which($cmd) { get-command $cmd | % { $_.Path } }
PS C:\> which devcon
C:\local\code\bin\devcon.exe
Tente o where
comando no Windows 2003 ou posterior (ou Windows 2000/XP se você tiver instalado um Kit de Recursos).
Aliás, isso recebeu mais respostas em outras perguntas:
Uma combinação rápida e suja com o Unix which
é
New-Alias which where.exe
Mas ele retorna várias linhas, se existirem, então fica
$(where.exe command | select -first 1)
Eu gosto Get-Command | Format-List
, ou mais curto, usando aliases para os dois e apenas para powershell.exe
:
gcm powershell | fl
Você pode encontrar aliases como este:
alias -definition Format-List
O preenchimento da guia funciona com gcm
.
eu tenho isto which
função avançada em meu perfil do 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 }
}
}
Usar:
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"
}
Ou esta versão, chamando o comando where original.
Esta versão também funciona melhor, pois não se limita a arquivos 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'
}