Search code examples
windowspowershellwmi

How to assign variable names to each for loop item - Powershell


I would like to be able to iterate through an array of monitors for a computer (pulled through WMI) and then assign each one its own value, so that I can output the results to a csv, with each monitor, mfg, date,sn on its own column.

For example:

Monitor 1 MFG     Monitor 1 SN     Monitor 2 MFG     Monitor 2 SN
   Dell                12345          HP                05156 


I know how to output to a csv already, just am having problems assiging each to its own variable to use.

$Monitors = Get-WmiObject -Namespace root\wmi -Class wmiMonitorID -ComputerName "PC"
$Monitors | % {$i=0} {"$_";$i++}

This gets me each instance name of each monitor on the machine, but how would I go about grabbing the Serial etc for each ?

I tried using $_.SerialNumberID to pull it out, but am unable to figure it out


Solution

  • Well...here is how you would do it. It looks like the data for some of the things in wmi needs to be converted to be readable.

    $Monitors = Get-WmiObject -Namespace root\wmi -Class wmiMonitorID    
    $obj = Foreach ($Monitor in $Monitors)
    {
        [pscustomobject] @{
        'MonitorMFG' = [char[]]$Monitor.ManufacturerName -join ''
        'MonitorSerial' = [char[]]$monitor.SerialNumberID -join ''
        'MonitorMFGDate' = $Monitor.YearOfManufacture
        }
    }
    $obj
    $obj | export-csv 
    

    Edit...alternative that more closely matches the formatting you are wanting...I think the above is better though personally.

    $Monitors = Get-WmiObject -Namespace root\wmi -Class wmiMonitorID
    $i = 1
    $obj = new-object -type psobject
    Foreach ($Monitor in $Monitors)
        {
        $obj | add-member -Name ("Monitor$i" +"MFG") -Value ([char[]]$Monitor.ManufacturerName -join '') -MemberType NoteProperty -Force
        $obj | add-member -Name ("Monitor$i" + "Serial") -Value ([char[]]$monitor.SerialNumberID -join '') -MemberType NoteProperty -Force
        $obj | add-member -Name ("Monitor$i" + "MFGDate") -Value ($Monitor.YearOfManufacture) -MemberType NoteProperty -Force    
        $i++   
        }
    $obj
    $obj | export-csv