我如何问PowerShell的东西在哪里?
例如,"which notepad",它根据当前路径返回notepad.exe运行的目录。
我如何问PowerShell的东西在哪里?
例如,"which notepad",它根据当前路径返回notepad.exe运行的目录。
当前回答
这是一个实际的*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
其他回答
当我开始在PowerShell中定制我的个人资料时,我做的第一个别名是“which”。
New-Alias which get-command
要将此添加到您的配置文件中,请键入以下内容:
"`nNew-Alias which get-command" | add-content $profile
最后一行开头的' n是为了确保它将作为一个新行开始。
Use:
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'
}
与Unix的快速匹配
New-Alias which where.exe
但如果它们存在,它会返回多行,然后它就变成
function which {where.exe command | select -first 1}
可以从https://goprogram.co.uk/software/commands安装which命令,以及所有其他UNIX命令。
我通常只输入:
gcm notepad
or
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
您将获得与您正在查找的内容相匹配的目录和命令。