首页 > 解决方案 > 使用通配符比较两个数组

问题描述

我正在尝试比较计算机上的添加/删除程序,并希望将其与文件共享上的软件列表进行比较,以便帮助台知道他们需要安装哪些许可软件。我创建了以下脚本,由于某种原因,我收到了我缺少括号的错误。我认为语法很好,或者我错过了什么?

我真的很感谢你的帮助

$approvedSoftware = @(Get-ChildItem -Path '\\fileshare\Applications'| Select-Object Name)

$computer= @(Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName)


foreach ($program in $computer)
{
if ("*$program*" -like $approvedSoftware)
{
Write-Host "$($program)"
}
}



标签: powershell

解决方案


我已经从评论中稍微更新了您建议的输入数据,因此两个数组中都有 1 个相同

样本输入数据:

$computer = "LogMeIn Rescue Technician Console;Microsoft Visual C++ 2013,Redistributable (x64) - 12.0.40649;Microsoft Visual C++ 2019 X86 Additional Runtime - 14.28.29910;MSXML 4.0 SP2 Parser;SDK".split(";")
$approvedSoftware = "Microsoft .NET Framework 4.7.1;Microsoft C++ Build Tools 2019;Microsoft Office Professional Plus 2016;Microsoft Office Project Professional 2010;Microsoft Visual C++ 2013,Redistributable (x64) - 12.0.40649".split(";")

输入数据需要是 2 个字符串数组或具有相同属性名称的对象进行比较。

在这些数组上运行Compare-Object后,您可以选择任何标准来根据SideIndicator属性过滤结果:

$Result = Compare-Object $computer $approvedSoftware -IncludeEqual
$Result

InputObject                                                    SideIndicator
-----------                                                    -------------
Microsoft Visual C++ 2013,Redistributable (x64) - 12.0.40649   ==
Microsoft .NET Framework 4.7.1                                 =>
Microsoft C++ Build Tools 2019                                 =>
Microsoft Office Professional Plus 2016                        =>
Microsoft Office Project Professional 2010                     =>
LogMeIn Rescue Technician Console                              <=
Microsoft Visual C++ 2019 X86 Additional Runtime - 14.28.29910 <=
MSXML 4.0 SP2 Parser                                           <=
SDK                                                            <=

$Result | ?{$_.SideIndicator -eq "=="}

InputObject                                                    SideIndicator
-----------                                                    -------------
Microsoft Visual C++ 2013,Redistributable (x64) - 12.0.40649   ==

根据您列出已安装软件的代码和批准列表中的代码,您需要执行以下操作:

$approvedSoftware = (Get-ChildItem -Path '\\fileshare\Applications').Name    
$computer = (Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*).DisplayName
$installedApprovedSoftware = (Compare-Object $computer $approvedSoftware -IncludeEqual `
  | Where {$_.SideIndicator -eq "=="}).InputObject
$installedApprovedSoftware | Foreach {Write-Host $_}

Microsoft Visual C++ 2013,Redistributable (x64) - 12.0.40649

我不确定您对基于输入数据的通配符的要求,但提供了有关如何-like使用通配符的参考。

参考:

Compare-Object文档:

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/compare-object?view=powershell-7.1

通配符比较的详细答案:

使用包含通配符条件的数组时出现问题


推荐阅读