ForEach Loop Export to CSV file

Welcome Forums General PowerShell Q&A ForEach Loop Export to CSV file

This topic contains 3 replies, has 3 voices, and was last updated by

 
Participant
4 months, 1 week ago.

  • Author
    Posts
  • #129872

    Participant
    Points: 32
    Rank: Member

    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
    }

  • #129879

    Participant
    Points: 167
    Helping Hand
    Rank: Participant

    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
    }
  • #129915

    Participant
    Points: 639
    Helping Hand
    Rank: Major Contributor

    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
    
  • #130010

    Participant
    Points: 32
    Rank: Member

    Thanks a lot Rob Simmers, it is working fine.

The topic ‘ForEach Loop Export to CSV file’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort