System.String export to csv

This topic contains 3 replies, has 2 voices, and was last updated by  JC 2 years, 3 months ago.

  • Author
    Posts
  • #29386

    JC
    Participant

    I'm trying to get all permanent routes off remote servers and I started with the following
    $Computers = "."

    $PermRoutes = get-wmiobject -class "Win32_IP4PersistedRouteTable" -namespace "root\CIMV2" -computername $Computers

    $routes = foreach ($object in $PermRoutes) {

    $object.Description

    }
    $routes | Export-CSV .\routes.csv -NoTypeInformation

    which displays a nice list of routes
    like 10.0.0.2,255.255.0.0,169.30.1.1,1
    however my csv only contains the $routes.Length property. I'm really bad with tables and arrays and not sure why instead of coma separated values I get only one value which is Length. Could someone explain what's going on in the script so I understand why I'm not getting what I expect?

  • #29388

    Chris Wolfenden
    Participant

    Take a look at:

    http://blogs.technet.com/b/heyscriptingguy/archive/2011/09/23/use-powershell-to-work-with-csv-formatted-text.aspx

    If you just want to export the data you can just use Out-File:

    $routes | Out-File .\routes.csv
    

    However, if you plan on building on this and pulling more data it may make sense change to a custom object:

    $PermRoutes = get-wmiobject -class "Win32_IP4PersistedRouteTable" -namespace "root\CIMV2" -computername $Computers
    
    $routes = foreach ($object in $PermRoutes) {
        [PSCustomObject]@{
    
                        Description = $object.Description
                        # You can add in addtional Properties
                        #ComputerName = $object.PSComputerName
                        #RouteName = $object.Name
    }
    
    $routes | Export-CSV .\routes.csv -NoTypeInformation
    
  • #29389

    Chris Wolfenden
    Participant

    An even simpler approach would be to just use a select statement:

    $PermRoutes = get-wmiobject -class "Win32_IP4PersistedRouteTable" -namespace "root\CIMV2" -computername $Computers
    
    $PermRoutes | Select-Object -Property Description | Export-CSV .\routes.csv -NoTypeInformation
    
  • #29401

    JC
    Participant

    Thanks Chris for great explanation. I see you use the PSCustomObject in a quite different way than the Scripting Guy does and to me less confusing. The 2-liner makes things even easier.

You must be logged in to reply to this topic.