Author Posts

September 4, 2015 at 8:01 am

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?

September 4, 2015 at 8:53 am

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

September 4, 2015 at 9:06 am

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

September 6, 2015 at 1:50 am

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.