循环内循环?

时间:2016-12-27 15:12:45

标签: powershell

尝试使用DisplayName值的-match搜索某些软件的注册表的卸载字符串。我可以让它与一个软件一起工作,但我遇到了麻烦,弄清楚如何让它与软件列表一起工作。例如,我将Java,Silverlight,Shockwave,Adobe Reader和Adobe Font Pack设置为变量,但无法弄清楚如何通过foreach命令循环它们。

$PATHS = @("HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall",
           "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall")

# Java 8 Update 102 | 8.0.1020.14
$Javax86 = "Java 8"

# Microsoft Silverlight | 5.1.50901.0
$MSsilverlight = "Microsoft Silverlight"

# Adobe Shockwave Player 12.2 | 12.2.5.195
$AdobeShockwave = "Adobe Shockwave Player"

# Extended Asian Language font pack for Adobe Acrobat Reader DC | 15.007.20033
$AdobeReaderFont = "font pack for Adobe Acrobat Reader"

# Adobe Acrobat Reader DC MUI | 15.020.20042
$AdobeReader = "Adobe Acrobat Reader DC MUI"

$SOFTWARE = "" 
#@($Javax86,$MSsilverlight,$AdobeShockwave,$AdobeReaderFont,$AdobeReader)

foreach ($path in $PATHS) {
    $installed = Get-ChildItem -Path $path |
                 foreach { Get-ItemProperty $_.PSPath } |
                 Where-Object { $_.DisplayName -match "$MSsilverlight" } |
                 Select-Object -Property DisplayName,DisplayVersion

    foreach ($app in $installed) {
        $DisplayName = "$($app.DisplayName)"
        $DisplayVersion = "$($app.DisplayVersion)"
    }

    if ($app.DisplayName) {
        $InstalledYes = "$DisplayName ($DisplayVersion) is installed"
    } elseif ($app.DisplayName -eq $NULL) {
        $InstalledNo = "$MSsilverlight is not Installed"
        #Write-Host "$SOFTWARE is not installed"
    }
}

Write-Host "$InstalledYes"
Write-Host "$InstalledNo"

1 个答案:

答案 0 :(得分:3)

当您使用-match运算符时,可以使用正则表达式运算符。不使用构建数组,而是使用管道分隔的字符串:

$SOFTWARE = "$Javax86|$MSsilverlight|$AdobeShockwave|$AdobeReaderFont|$AdobeReader"

ForEach ($path in $PATHS) {

    $installed = Get-ChildItem -Path $path | 
                 ForEach { Get-ItemProperty $_.PSPath } | 
                 Where-Object { $_.DisplayName -match $SOFTWARE } | 
                 Select-Object -Property DisplayName,DisplayVersion

    ForEach ($app in $installed) {
       $DisplayName = "$($app.DisplayName)"
       $DisplayVersion = "$($app.DisplayVersion)"

    }

    ....