2008-09-15 12 views

Respuesta

243

El primer alias que hice una vez que comencé a personalizar mi perfil en powershell era 'which'.

New-Alias which get-command 

Para añadir esto a su perfil, escriba lo siguiente:

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

El `n es asegurar que comenzará como una nueva línea.

+1

gracias, ¿dónde pongo esto para que se adhiera? – DevelopingChris

+1

Puedes ponerlo en tu script de perfil. Más información sobre perfiles: http://msdn.microsoft.com/en-us/library/bb613488(VS.85).aspx –

+0

He editado anteriormente para responder a su pregunta ChanChan – halr9000

3

Esto parece hacer lo que quiere (lo encontré en 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 
+0

Pero no es realmente "que" ya que funciona con cualquier archivo (tipo) y no encuentra cmdlets, funciones o alias – Jaykul

3

Marque esta Powershell Which

El código siempre que sugiere este

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

que conozco lleva años, pero mi ruta tenía "% systemroot% \ system32 \ ..." y PowerShell no expande esa variable de entorno y arroja errores al hacer esto. – TessellatingHeckler

63

por lo general sólo tiene que escribir:

gcm notepad 

o

gcm note* 

GCM es el alias predeterminado de Get-Command.

En mi sistema, GCM nota * salidas:

[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 

Se obtiene el directorio y el comando que coincide con lo que estás buscando.

+0

es un poco desordenado, pero mucho más limpio que las funciones personalizadas y las divisiones arbitrarias – DevelopingChris

+0

Cuando escribo "gcm notepad" en el símbolo del sistema de powershell, obtengo las dos primeras columnas y una tercera columna llamada 'ModuleName' que está vacía. ¿Sabes cómo forzarlo a listar la columna 'Definición' por defecto? –

+2

@PiyushSoni que es probablemente debido a una versión actualizada de PowerShell. Siempre puede mostrar las otras columnas haciendo algo como 'gcm note * | seleccione CommandType, Name, Definition'. Si lo ejecuta a menudo, probablemente debería envolverlo en una función. –

2

intentar el comando where en Windows 2003 o posterior (o Windows 2000/XP si ha instalado un kit de recursos): http://ss64.com/nt/where.html

Por cierto, este recibió más respuestas en otros hilos:

Is there an equivalent of 'which' on windows?

Powershell equivalent to unix which command?

+2

'where' alias al comando' Where-Object' en Powershell, por lo que al escribir 'where ' en un mensaje de Powershell no se obtiene nada. Esta respuesta es, por lo tanto, completamente incorrecta: como se señala en la respuesta aceptada en la primera pregunta vinculada, para obtener el DOS 'donde', debe escribir' where.exe '. –

101

Aquí es un equivalente real * nix, es decir, da * salida de estilo nix.

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

Simplemente reemplace con lo que está buscando.

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

Cuando se suma a su perfil, tendrá que utilizar una función en lugar de un alias porque no se puede utilizar alias con tubos:

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

Ahora, cuando vuelva a cargar su perfil usted puede hacer esto:

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

Utilizo esta sintaxis alternativa: "(Get-Command notepad) .definition" – Yann

+0

@ B00merang Su sintaxis es excelente, definitivamente más conciso, pero desafortunadamente, incluso con la tubería eliminada, no se puede agregar como un alias a menos que incluye el nombre del programa que está buscando. – petrsnd

+0

perfecto! 1234567 – mbrownnyc

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

O esta versión, llamar al comando donde originales. Esta versión también funciona mejor, porque no se limita a los archivos de murciélago

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' 
} 
30

Prueba este ejemplo:

(Get-Command notepad.exe).Path 
+1

Agregue más código o explicación para que el OP pueda entenderlo mejor. Gracias. – sshashank124

+3

Gracias por agregar menos código, así que puedo recordar esto por una vez: P – albertjan

+1

¡Esto es lo que quería! También funciona con gcm: '(gcm py.exe) .path' –

1

Mi propuesta para la función que:

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

PS C:\> which devcon

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

2

Un partido quickndirty a Unix which es

New-Alias which where.exe 

Pero devuelve varias líneas si es que existen por lo que entonces se convierte en

$(where.exe command | select -first 1)

+0

' where.exe where' debería decirle 'C: \ Windows \ System32 \ where.exe' –

+0

' where.exe' es equivalente a 'which -a', ya que devolverá * todos * ejecutables coincidentes, no solo el primero que se ejecutará. Es decir, 'where.exe notepad' da' c: \ windows \ notepad.exe' y 'c: \ windows \ system32 \ notepad.exe'. Por lo tanto, esto es particularmente * no * adecuado para la forma '$ (which command)'. (Otro problema es que imprimirá un mensaje de error útil y útil si no se encuentra el comando, que tampoco se expandirá muy bien en '$()' - que se puede solucionar con '/ Q', pero no como un alias .) –

+0

punto tomado. Edité la respuesta, pero sí, ya no es una solución tan clara –

0

me gusta get-command | formato de lista, o:

gcm powershell | fl 

puede encontrar alias como este:

alias -definition format-list 

finalización Tab funciona con GCM.

0

tengo unas pocas cosas which función avanzada de perfil 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 } 
    } 
} 
Cuestiones relacionadas