命令行与文本处理 / 系统课时

使用 Get-Command 查找命令

使用 Get-Command 查找命令

Get-Command 是 PowerShell 的命令发现入口。你可以用它搜索 Cmdlet、函数、别名、脚本和外部程序,再叠加模块、类型或参数条件,把模糊需求缩小为可验证的候选命令。

学习目标

  • 使用名称和通配符搜索可用命令
  • 按命令类型、模块和参数条件缩小结果
  • 识别命令冲突,并查看最终解析到的对象

先掌握查询入口

不带参数运行 Get-Command 会列出当前会话可见的大量命令,通常不适合作为第一步。更实用的做法是先给 -Name,并在不确定完整名称时使用 * 通配符。

-CommandType 可限制为 Cmdlet、Function、Alias、ExternalScript 或 Application;-Module 可限制来源模块;-ParameterName 和 -ParameterType 可按命令支持的参数继续筛选。多个条件组合后,结果必须同时满足这些条件。

查找不同类型的命令

下面的脚本同时演示通配符搜索、按模块和参数查找 Cmdlet,以及定位别名、函数和外部程序。

powershell
$wildcardMatches = Get-Command -Name 'Get-*Item*' -CommandType Cmdlet

$cmdletQuery = @{
    Name          = 'Get-ChildItem'
    CommandType   = 'Cmdlet'
    Module        = 'Microsoft.PowerShell.Management'
    ParameterName = @('Path', 'Recurse')
}
$cmdlet = Get-Command @cmdletQuery

$alias = Get-Command -Name 'gci' -CommandType Alias
$function = Get-Command -Name 'prompt' -CommandType Function
$app = Get-Command -Name 'pwsh' -CommandType Application |
    Select-Object -First 1

@(
    [pscustomobject]@{
        Search = 'Get-*Item*'
        Type   = 'Cmdlet'
        Result = '{0} match(es)' -f $wildcardMatches.Count
    }
    [pscustomobject]@{
        Search = 'Get-ChildItem'
        Type   = $cmdlet.CommandType
        Result = $cmdlet.Name
    }
    [pscustomobject]@{
        Search = 'gci'
        Type   = $alias.CommandType
        Result = $alias.Definition
    }
    [pscustomobject]@{
        Search = 'prompt'
        Type   = $function.CommandType
        Result = '<session function>'
    }
    [pscustomobject]@{
        Search = 'pwsh'
        Type   = $app.CommandType
        Result = $app.Path
    }
) | Format-Table -AutoSize

预期输出

text
Search        Type        Result
------        ----        ------
Get-*Item*    Cmdlet      <COUNT> match(es)
Get-ChildItem Cmdlet      Get-ChildItem
gci           Alias       Get-ChildItem
prompt        Function    <session function>
pwsh          Application <PATH>

<COUNT> 会随已加载模块和 PowerShell 版本变化,<PATH> 会随操作系统与安装位置变化。关键验证点是:精确查询返回 Get-ChildItem,别名 gci 的目标为 Get-ChildItem,而 pwsh 被识别为外部程序。

处理同名命令与优先级

当多个命令同名时,PowerShell 通常按别名、函数、Cmdlet、外部程序的顺序解析。Get-Command Name 默认显示优先匹配项,使用 Get-Command Name -All 才能查看全部候选。

结果中的 Source 常用于识别模块来源,Definition 可查看别名目标或函数定义,Path 可查看脚本和外部程序位置。发现来源异常时,应优先检查当前会话中新建的别名或函数,以及 PATH 中靠前的可执行文件。

从结果继续探索

找到候选命令后,可使用 Get-Command <名称> -Syntax 快速查看参数组合,再用 Get-Help <名称> -Full 阅读完整帮助。只知道参数名时,先用 -ParameterName 反向搜索,通常比逐个打开帮助更高效。

不要在脚本中仅凭别名或外部程序名称假定行为。先确认 CommandType、Source 或 Path,可以避免调用到被覆盖的函数、错误模块版本或同名可执行文件。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

使用 Get-Command 查找命令

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通