PowerShell中使用WMIC命令如何仅获取数值输出,去除变量名?
解决WMIC输出提取数值并判断的问题
方法1:处理WMIC命令的输出
WMIC的输出自带表头和空行,你可以通过过滤和格式化提取纯数值:
# 提取DEPPolicy数值 $depValue = wmic OS Get DataExecutionPrevention_SupportPolicy | Where-Object { $_ -match '\d+' } | ForEach-Object { [int]$_.Trim() } # 按预期数值判断并输出$true(示例预期为2,可自行修改) if ($depValue -eq 2) { Write-Output $true }
Where-Object { $_ -match '\d+' }:过滤出包含数字的行,自动跳过表头和空行[int]$_.Trim():去除字符串前后空格并转换为整数类型
方法2:用PowerShell原生CIM命令(推荐)
WMIC是旧工具,PowerShell原生的Get-CimInstance能直接返回结构化对象,无需处理格式问题:
# 直接获取目标属性值 $depValue = (Get-CimInstance -ClassName Win32_OperatingSystem).DataExecutionPrevention_SupportPolicy # 判断并输出结果 if ($depValue -eq 2) { Write-Output $true }
这种方式更简洁可靠,避免了字符串解析的潜在问题。
内容的提问来源于stack exchange,提问作者PS-Junior
相关产品推荐
相关产品推荐

