powershell - Export computer information to a CSV -


the code below outputs information like:

system information for: localhost    model          : {0}    serial number  : {1}    version        : {2}    monitor model  : {3}   monitor serial : {4} 

how export csv , have formatting in excel like:

name,  model,  serial number,   version,   monitor model,  monitor serial 

i each value in own cell.

code 1:

$arrcomputers = "localhost" $outputlog = ".\output.log"  $notrespondinglog = ".\notresponding.log"  $erroractionpreference = "stop"  clear-host  foreach ($computer in $arrcomputers) {   try {     $computersystem = get-wmiobject win32_computersystem -computer $computer     $computerbios = get-wmiobject win32_bios -computer $computer     $version = get-wmiobject -namespace "root\cimv2" `         -query "select * win32_computersystemproduct" `         -computer $computer | select -expandproperty version     $monitorinfo = gwmi wmimonitorid -namespace root\wmi -computername  $computer |       select -last 1 @{n="model"; e={[system.text.encoding]::ascii.getstring($_.userfriendlyname -ne 00)}},         @{n="serial number";e={[system.text.encoding]::ascii.getstring($_.serialnumberid -ne 00)}}     } catch {     $computer | out-file -filepath $notrespondinglog -append -encoding utf8     continue   }    $header = "system information for: {0}" -f $computersystem.name    write-host $header -backgroundcolor darkcyan   $header | out-file -filepath $outputlog -append -encoding utf8    $output = (@"   -------------------------------------------------------    model          : {0}    serial number  : {1}    version        : {2}    monitor model  : {3}   monitor serial : {4}    -------------------------------------------------------  "@) -f -join $computersystem.model, $computerbios.serialnumber, $version, `     $monitorinfo.model, $monitorinfo."serial number"    write-host $output   $output | out-file -filepath $outputlog  -append -encoding utf8 } 

drop format string , export data csv:

$data = foreach ($computer in $arrcomputers) {   try {     ...   } catch {     ...   }    $props = [ordered]@{     'name'           = $computersystem.name     'model'          = $computersystem.model     'serial number'  = $computerbios.serialnumber     'version'        = $version     'monitor model'  = $monitorinfo.model     'monitor serial' = $monitorinfo."serial number"   }   new-object -type pscustomobject -property $props }  $data | export-csv 'c:\path\to\output.csv' -notype 

the new-object statement required, because export-csv exports properties of list of objects fields of csv file.

beware excel rather particular accepts csv. file must must comma-separated (regardless of field separator configured in system's regional settings).


Comments