You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中Where-Object返回不匹配值的问题排查

问题描述

我有一个存储Windows补丁和CVE编号信息的PSObject集合,单条记录格式如下:

ID                  : 2022-Sep
InitialRealeaseDate : 13/09/2022 07:00:00
CvrfUrl             : https://api.msrc.microsoft.com/cvrf/v2.0/document/2022-Sep
Severity            :
DocumentTitle       : September 2022 Security Updates
cve                 : CVE-2022-37969
Alias               : 2022-Sep
CurrentReleaseDate  : 04/10/2022 07:00:00

我尝试提取匹配指定CVE的记录,使用了如下命令:

$results | where {$results.cve -eq 'CVE-2022-38006'}

但该命令返回了多条记录(包含正确的那条),其中大多数记录的cve字段与筛选条件完全不匹配。通过Get-Member查看,cve字段为字符串类型:

PS E:\Scripts\Ian\GIT\XDR> $results | gm

   TypeName: System.Management.Automation.PSCustomObject

Name                MemberType   Definition
----                ----------   ----------
Equals              Method       bool Equals(System.Object obj)
GetHashCode         Method       int GetHashCode()
GetType             Method       type GetType()
ToString            Method       string ToString()
Alias               NoteProperty string Alias=2022-Sep
CurrentReleaseDate  NoteProperty string CurrentReleaseDate=04/10/2022 07:00:00
cve                 NoteProperty string cve=
CvrfUrl             NoteProperty string CvrfUrl=https://api.msrc.microsoft.com/cvrf/v2.0/document/2022-Sep
DocumentTitle       NoteProperty string DocumentTitle=September 2022 Security Updates
ID                  NoteProperty string ID=2022-Sep
InitialRealeaseDate NoteProperty string InitialRealeaseDate=13/09/2022 07:00:00
Severity            NoteProperty string Severity=

请问我哪里操作错误?

问题原因与解决方法
  • 错误原因:在Where-Object(别名where)的脚本块中,你错误引用了整个集合的$results.cve属性,而非当前迭代的单个对象。PowerShell对数组执行-eq比较时,只要数组内存在一个匹配元素,整个表达式就会返回$true,导致所有记录都被保留。
  • 解决方法:使用$_(或$PSItem)指代当前处理的对象,修正后的命令如下:
$results | Where-Object { $_.cve -eq 'CVE-2022-38006' }

这样就能精准筛选出cve字段完全匹配指定值的记录。

内容的提问来源于stack exchange,提问作者sailingbikeruk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 16:15:49