首页 > 解决方案 > PowerShell Where-Object - 没有返回 - 我一定做错了什么

问题描述

我运行以下命令并没有收到任何回报 - 我查看了 reg 并验证了显示名称是否存在。知道我做错了什么吗?

$OfficeYearsToLookFor = @(
'2010',
'2013',
'2016',
'2019')

$status = (Get-ItemProperty 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'  | 
Where-Object {(($_.DisplayName -contains 'Office') -and ($_.DisplayName -contains 'Microsoft') -and ( $OfficeYearsToLookFor -contains $_.DisplayName )) } | 
Select-Object DisplayName, DisplayVersion, UninstallString )
$status
Write-Output "Status: $status"

标签: powershellpowershell-3.0powershell-remoting

解决方案


您可能只是使这个用例过于复杂。只需使用简单的 RegEx 匹配即可。该Where-Object声明并不是真正需要的。例如:

正则表达式匹配以获取与字符串和数字模式匹配的所有内容

(Get-ItemProperty 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*') -match '.*Microsoft.*Office.*\d{4}.*' | 
Select-Object -Property DisplayName, DisplayVersion, UninstallString 
# Results
<#
DisplayName                                                        DisplayVersion   UninstallString
-----------                                                        --------------   ---------------
Microsoft Project - en-us                                          16.0.13801.20360 "C:\Program Files\...
Microsoft Office Professional Plus 2016 - en-us                    16.0.13801.20360 "C:\Program Files\...
...
Office 16 Click-to-Run Licensing Component                         16.0.13801.20360 MsiExec.exe /...                                                                             
...
#>  

正则表达式匹配以获取与字符串和数字模式匹配的所有内容,并仅选择所需的属性和年份字符串匹配的行

((Get-ItemProperty 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*') -match '.*Microsoft.*Office.*\d{4}.*' | 
Select-Object -Property DisplayName, DisplayVersion, UninstallString ) -match '2010|2013|2016|2019'
# Results
<#
DisplayName                                     DisplayVersion   UninstallString
-----------                                     --------------   ---------------
Microsoft Office Professional Plus 2016 - en-us 16.0.13801.20360 "C:\Program Files\...
#>

推荐阅读