Home > Enterprise >  Variable not exporting in order
Variable not exporting in order

Time:10-28

$filename = 'c:\reports\mx-facebook.csv'

$MXRecord = Resolve-DnsName 'facebook.com' -Type mx -Server '8.8.8.8' -ErrorAction Stop

$MXRecord | Sort-Object -Property @{Expression = "Name"},@{Expression = "Type"},@{Expression = "TTL"},@{Expression = "Section"},@{Expression = "NameExchange"} | Export-Csv $filename -NoTypeInformation

I have tried exporting many different ways but as show above the output comes out of order like the following. I have done it without the calculated property as well and it still comes out of order.

"QueryType","Exchange","NameExchange","Preference","Name","Type","CharacterSet","Section","DataLength","TTL"
"MX","smtpin.vvv.facebook.com","smtpin.vvv.facebook.com","10","facebook.com","MX","Unicode","Answer","64","1563"

How can I export it in order like the following.

Name                                     Type   TTL   Section    NameExchange
----                                     ----   ---   -------    ------------
facebook.com                             MX     1563  Answer     smtpin.vvv.facebook.com

CodePudding user response:

You can specify the desired properties with Select-Object or make your own objects with [PSCustomObject] type accelerator

$MXRecord | Select-Object Name,Type,TTL,Section,NameExchange| Export-Csv $filename -NoTypeInformation

or

$MXRecord | ForEach-Object {
    [PSCustomObject]@{
        Name         = $_.name
        Type         = $_.type
        TTL          = $_.ttl
        Section      = $_.section
        NameExchange = $_.nameexchange
    }
} | Export-Csv $filename -NoTypeInformation
  • Related