How to use nested ForEach-Object

47 Views Asked by At

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 $_
    }
}
1

There are 1 best solutions below

2
lit On BEST ANSWER

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
        }
}