ForEach Loop Export to CSV file

We have a script to find a registry key as below. How can i export the result to CSV file ?

$main = “Localmachine”
$Path = “SOFTWARE\Microsoft\MSMQ\Parameters”
$key = “Workgroup”
$servers = Get-ADComputer -Filter ‘*’ | select -expand name
foreach ($Server in $servers)
{
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($main, $Server)
$regKey= $reg.OpenSubKey($path)
$Value = $regkey.GetValue($key)
Write-Host $Server, $Value
}

Look at the Export-CSV and Out-file cmdlets for starters:

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/export-csv?view=powershell-6

https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Out-File?view=powershell-6

This may do what you want, but its untested…

$main = "Localmachine"
$Path = "SOFTWARE\Microsoft\MSMQ\Parameters"
$key = "Workgroup"
$servers = Get-ADComputer -Filter '*' | select -expand name
foreach ($Server in $servers)
{
 $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($main, $Server)
 $regKey= $reg.OpenSubKey($path)
 $Value = $regkey.GetValue($key)
 "`"$regkey`",`"$Value`"" | out-file export.csv -append
}

Recommend you add error handling and I typically collect all results and then do something with them, something like this:

$main = "Localmachine"
$Path = "SOFTWARE\Microsoft\MSMQ\Parameters"
$key = "Workgroup"
$servers = Get-ADComputer -Filter '*' | select -expand name
$results = foreach ($Server in $servers) {
    try {
        $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($main, $Server)
        $regKey= $reg.OpenSubKey($path)
        $Value = $regkey.GetValue($key)
    }
    catch {
        $regKey = $Null
        $Value = $_
    }

    [pscustomobject]@{
        ComputerName = $Server
        Key = $regkey
        Value = $Value
    }
}

$results | Export-CSV -Path C:\RegistryQuery.csv -NoTypeInformation

Thanks a lot Rob Simmers, it is working fine.