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

PowerShell通过注册表获取已安装软件信息的匹配与变量设置问题

问题分析与解决方案

你遇到的问题核心是对PowerShell的-contains操作符理解有误——-contains是用来判断集合是否包含某个元素,不是字符串包含判断。比如你用"Microsoft Office 2022" -contains "2022"会返回False,因为它在判断整个字符串是否等于"2022",而非字符串里是否包含这个子串。

正确的字符串包含判断方法

针对字符串包含特定版本号的场景,推荐以下三种方式:

1. 使用通配符操作符 -like

这是PowerShell里最常用的字符串模糊匹配方式,用*匹配任意长度的字符:

$displayName -like "*2022*"

2. 使用正则匹配操作符 -match

如果需要更灵活的匹配(比如版本号格式校验),可以用正则:

$displayName -match "2022"

3. 使用字符串原生方法 .Contains()

直接调用.NET字符串的Contains方法,区分大小写(如果要忽略大小写可以用.IndexOf()配合[StringComparison]::OrdinalIgnoreCase):

$displayName.Contains("2022")

完整脚本示例

下面是结合注册表读取的完整实现,满足你的需求:

# 初始化变量
$versionFound = $false
$targetInstallPath = $null

# 遍历Uninstall注册表项
Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall | ForEach-Object {
    $displayName = $_.GetValue("DisplayName")
    $installLocation = $_.GetValue("InstallLocation")

    # 判断DisplayName是否包含"2022"
    if ($displayName -like "*2022*" -and $installLocation) {
        $versionFound = $true
        $targetInstallPath = $installLocation
        # 如果只需要第一个匹配项,这里可以加break跳出循环
        # break
    }
}

# 输出结果
Write-Host "版本标识: $versionFound"
if ($versionFound) {
    Write-Host "安装路径: $targetInstallPath"
}

额外说明

  • 如果需要同时匹配32位和64位软件,记得加上HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall路径一起遍历
  • 如果要忽略大小写匹配,-like可以改成-ilike,-match改成-imatch,.Contains()可以换成$displayName.IndexOf("2022", [StringComparison]::OrdinalIgnoreCase) -ge 0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 11:12:02