如何在PowerShell的foreach循环中输出DisplayVersion属性至结果?
为程序安装检测脚本添加版本字段输出
需求:修改现有PowerShell脚本,使其输出包含Program、Status、Match、Version四个字段,其中Version对应应用的DisplayVersion注册表属性。示例输出格式如下:
Program Status Match Version ------- ------ ----- ------- SAP Found SAP GUI for Windows 7.60 (Patch 4) 7.60.4
原脚本代码
$programList = @( 'SAP' 'Tanium' 'Sentinel' 'DisplayLink' 'Cisco AnyConnect' 'Adobe Acrobat Reader' 'Google' 'Lotus Notes' 'Java Runtime' 'My IT Windows' 'Qualys' 'Snow' 'LogRhythm' ) $Regpath = @( 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*' 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' ) $installedPrograms = (Get-ItemProperty $Regpath).where({$_.DisplayName}) $result = foreach($program in $programList) { $check = $installedPrograms.DisplayName -match $program if($check) { foreach($match in $check) { [pscustomobject]@{ Program = $program Status = 'Found' Match = $match } } continue } [pscustomobject]@{ Program = $program Status = 'Not Found' Match = $null version = $null } } $result
修改后的脚本代码
$programList = @( 'SAP' 'Tanium' 'Sentinel' 'DisplayLink' 'Cisco AnyConnect' 'Adobe Acrobat Reader' 'Google' 'Lotus Notes' 'Java Runtime' 'My IT Windows' 'Qualys' 'Snow' 'LogRhythm' ) $Regpath = @( 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*' 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' ) $installedPrograms = (Get-ItemProperty $Regpath).where({$_.DisplayName}) $result = foreach($program in $programList) { # 筛选出DisplayName匹配当前程序的完整对象,保留所有属性 $matchingPrograms = $installedPrograms | Where-Object { $_.DisplayName -match $program } if($matchingPrograms) { foreach($item in $matchingPrograms) { [pscustomobject]@{ Program = $program Status = 'Found' Match = $item.DisplayName Version = $item.DisplayVersion # 添加版本字段 } } continue } [pscustomobject]@{ Program = $program Status = 'Not Found' Match = $null Version = $null # 统一字段大小写为Version } } $result | Format-Table -AutoSize # 自动调整表格列宽,优化显示
修改说明
- 原脚本仅提取了匹配的
DisplayName字符串,无法获取对应的版本信息,修改后直接筛选完整的程序注册表对象,保留DisplayVersion属性。 - 在生成结果对象时,新增
Version字段,直接从匹配到的对象中提取DisplayVersion值。 - 统一未找到程序时的字段名为
Version(原脚本为小写version),保持字段名一致性。 - 最后添加
Format-Table -AutoSize,让输出表格自动适配列宽,可读性更强。
内容的提问来源于stack exchange,提问作者PowerShellBeginner
相关产品推荐
相关产品推荐

