Export command output into two columns CSV file

Recently I was looking for easy way to export output into two columns CSV file. Finding solution for this was a little bit difficult because some values of the properties were another objects or they were for example data.table types. Below you will find how to do this based on one of the ADFS module commands.

Get-AdfsRelyingPartyTrust

The Get-ADFSRelyingPartyTrust cmdlet retrieves the relying party trusts in the Federation Service. You can use this cmdlet with no parameters to get all relying party trust objects.

Normally when you want to get some specific relying party details you can query ADFS database by its identifier or name:

Get-AdfsRelyingPartyTrust -Name "Your Relying Party Name" 

Output of this query will be displayed in formatted list. However if you want to export it to CSV file then each property from results will be saved as a separated column:

CSV1
CSV1

I just wanted to create CSV file with two columns. One columns will be "Property" and the second one "Value". Final output should look like this:

CSV2
CSV2

Final script:


                # Table name
                $tabName = “RelyingParty”

                # Create Table object
                $table = New-Object system.Data.DataTable “$tabName”

                # Define Columns
                $col1 = New-Object system.Data.DataColumn "Property",([string])
                $col2 = New-Object system.Data.DataColumn "Value",([string])

                # Add the Columns
                $table.columns.add($col1)
                $table.columns.add($col2)

                # Input file
                $Server = "ADFS01"
                $RPDetails = Invoke-Command $Server -ScriptBlock{ Get-AdfsRelyingPartyTrust -Name "Your Relying Party Name" }
 
                Foreach ($line in $RPDetails) 
                {
                    Foreach ($property in (($RPDetails| Get-Member -MemberType Property).name)) 
                    {
                        $Value = $line.$property | Out-String
                        $Value = $Value.Trim() 

                        # Create a row
                        $row = $table.NewRow()
                        $row."Property" = $property
                        $row."Value" = $Value
                        $table.Rows.Add($row)
                    }
                }
                # Display in new pop-up window
                $table | Out-GridView

                # Export to CSV
                $table | Export-Csv -Path C:\users\$env:username\desktop\RPDetails.csv -NoTypeInformation

For more information about ADFS command please visit technet site.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.