在 PowerShell 中过滤对象条目

Filtering Objects entries in PowerShell

我今天开始玩PowerShell,想做一个简单的任务。阅读我安装的所有软件,过滤掉“Microsoft 相关条目 + 空条目”并将它们存储在 JSON 文件中。

好吧,我能够做到这一点,但我无法弄清楚过滤部分,主要是因为整个脚本语言对我来说是新的,我无法成功地迭代以删除我想要的条目。

感谢您的帮助!

$outputFile="C:\test.JSON"
$GetAppData= Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* |Select-Object DisplayName, DisplayVersion, InstallDate

    foreach ($Applications in $GetAppData.PSObject) 
    {

        foreach ($App in $Applications.Properties.Value) 
        {
         if ($App.'DisplayName' -like '*Microsoft*' -or !$App.'DisplayName' ) 
                {
                    $Applications.Value.PSObject.Properties.Remove($App)  
                }
         }
    }    
     
    $GetAppData| ConvertTo-Json -Depth 100 | Set-Content -Path $outputFile -Force

获取信息的更简单方法是使用较新的 Get-Package cmdlet。 [咧嘴一笑]

代码的作用...

  • 将项目模式设置为排除
    你可以把它变成一个正则表达式 OR 列表来排除一个以上的项目。
  • 获取所有包的列表
  • 过滤掉 MSU 项目
  • 过滤掉带空格的项目 .Name 属性
  • 过滤掉符合 $DoNotWant 模式的项目
  • 将列表保存到 $Result 集合
  • 在屏幕上显示列表

您可以添加其他步骤以按名称排序、重新排列属性或以其他方式自定义最终对象中的道具。

代码...

$DoNotWant = 'microsoft'

$Result = Get-Package |
    Where-Object {
        $_.ProviderName -ne 'msu' -and
        $_.Name -and
        $_.Name -notmatch $DoNotWant
        }

$Result

截断输出...

Name                           Version          Source                           ProviderName
----                           -------          ------                           ------------
7-Zip 19.00 (x64)              19.00                                             Programs
AutoHotkey 1.1.33.02           1.1.33.02                                         Programs
Bulk Rename Utility 3.3.2.1...                                                   Programs

[*...snip...*] 

PSFileTransfer                 5.31.0           https://www.powershellgallery... PowerShellGet
PSFramework                    1.4.150          https://www.powershellgallery... PowerShellGet
PSLog                          5.31.0           https://www.powershellgallery... PowerShellGet
PackageManagement              1.4.7            https://www.powershellgallery... PowerShellGet

对于您的具体问题,这是您过滤和导出 $GetAppData 的方法。有多种过滤数组的方法,也有一些 cmdlet / 函数可以为您提供与查询 HKLM 相同的结果。

$outputFile="C:\test.JSON"
$GetAppData= Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* |Select-Object DisplayName, DisplayVersion, InstallDate

$GetAppData.Where({$_.DisplayName -and $_.DisplayName -notmatch 'Microsoft'})|ConvertTo-Json > $outputFile

干杯!