约 1468 字

约 7 分钟

#PowerShell 的 Select-String 命令

Select-String [-Pattern] <String[]> [-Path] <String[]> [-SimpleMatch] [-CaseSensitive] [-AllMatches]
Select-String [-Pattern] <String[]> -LiteralPath <String[]> [-SimpleMatch] [-CaseSensitive] [-AllMatches]
文本 | Select-String [-Pattern] <String[]> [-SimpleMatch] [-CaseSensitive] [-AllMatches]

功能

在文件或管道输入中按行查找匹配的文本。默认返回 MatchInfo 对象,Line 属性是整行的文本,Matches 属性包含正则匹配详情。

类型

Cmdlet,属于 Microsoft.PowerShell.Utility。

参数

  • -Pattern <String[]> 用来指定一个或多个正则表达式。
  • -Path <String[]> 用来指定文件路径,支持通配符。-LiteralPath 按路径原样查找。
  • -SimpleMatch 用来按字面文本查找。
  • -CaseSensitive 让查找区分大小写。
  • -AllMatches 将同一行中的所有正则匹配放进该行的 Matches 属性。
  • -Quiet 只返回是否找到匹配的布尔值。

#示例

提取匹配的文本

$result = 'build=42', 'preview', 'build=57' | Select-String -Pattern '^build=\d+$'
$result | Select-Object -ExpandProperty Line
build=42
build=57

提取一行中的所有匹配

$result = 'ports: 80, 443' | Select-String -Pattern '\d+' -AllMatches
$result.Matches.Value
80
443

#推荐阅读

更新: 2026/11/27

作者: planc

创建: 2026/11/27