Search code examples
powershellforeachnested-loops

How to use nested ForEach-Object


How can I use nested ForEach-Object? The $_ is returns "HKCU:.." but I want to access "Microsoft Teams" string inside second ForEach-Object.

@(
    "Microsoft Teams",
    "Microsoft Teams Meeting Add-in for Microsoft Office",
    "Teams Machine-Wide Installer"
) | ForEach-Object {
    "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*",
    "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*",
    "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | ForEach-Object {
        Write-Host $_
    }
}

Solution

  • The $_ of the first ForEach-Object needs to be saved into a variable. Then, used inside the second ForEach-Object.

    @(
        "Microsoft Teams",
        "Microsoft Teams Meeting Add-in for Microsoft Office",
        "Teams Machine-Wide Installer"
    ) |
    ForEach-Object {
        $FirstItem = $_
        "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*",
        "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*",
        "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" |
            ForEach-Object {
                Write-Host $_
                Write-Host $FirstItem
            }
    }