PowerShell note for myself – Hashtables, arrays and their output to .csv in the wanted way

This is a note for myself to finally remember once and for all how to export a result to .csv file properly (with column headers in this case) using GetEnumerator()

#get pc names from somewhere
$allpc = Get-Content .\allpc.txt
#$allpc = @('pc1', 'pc2')
#Create Empty
$result = @()
#List below is there just for testing purposes
$list = New-Object 'Collections.Generic.List[string]'
#Loop through names and get needed data - in this case Computer Name, BIOS Data, Computer Model
foreach ($pc in $allpc) {
    if (Test-Connection -computername $pc -Count 1 -ErrorAction SilentlyContinue) {
        $checkBiosPassEN = (Get-WmiObject -computername $pc -Namespace root/hp/InstrumentedBIOS -Class HP_BIOSSetting | Where-Object Name -eq "Setup Password").IsSet
        $BiosData = Get-WmiObject -computername $pc -Class win32_bios
        $PCData = Get-WmiObject -computername $pc -Class Win32_computersystem 
        #Create Powershell object - ordered hashtable in this case
        $dataObj = [ordered]@{
            ComputerName    = $pc
            ComputerModel   = $PCData.Model
            BiosVersion     = $BiosData.SMBIOSBIOSVersion
            PasswordEnabled = $checkBiosPassEN
        #Add object to the result array
        $result += $dataObj
        #Add object to the list
        #Clear the object before next computer 
        $dataObj = ""
#Create .csv file with headers using enumerator to loop through array, selecting needed properties
$result.GetEnumerator() |
Select-Object -Property @{Name = 'ComputerName'; Expression = { $_.ComputerName } },
@{Name = 'ComputerModel'; Expression = { $_.ComputerModel } }, @{Name = 'BiosVersion'; Expression = { $_.BiosVersion } }, @{Name = "PasswordEnabled"; Expression = { $_.PasswordEnabled } } |
Export-Csv -NoTypeInformation -Path resultMOD.csv

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.