Question

First time poster here, I'm a bit of a beginner and I've been keen to get my PowerShell scripting skills up to scratch and I'm come across something rather confusing...

I've made a script to query a collection of computers and I want to query Win32_OperatingSystem but only extrapolate the Build number so I can populate my PSObject with it. I'm trying to add some If logic so that if the build number is 7601, I can write a message under my OS column.

The problem I'm having is that the BuildNumber values are coming out as @{BuildNumber=7601} instead of 7601 for instance. That, and my If statement is borked.

$Machines = Get-Content .\Computers.txt

Foreach($Machine in $Machines)
{
    $sweet = (Get-WmiObject -Class Win32_OperatingSystem -computer $Machine | Select-Object BuildNumber)
    $dversion = if ($sweet -eq "@{BuildNumber=7601}") {Yes!} else {"Nooooo!"}

    New-Object PSObject -Property @{
    ComputerName = $Machine
    Sweet = $sweet
    OS = $dversion

}
}
Was it helpful?

Solution

The issue is that the Get-WMIObject cmdlet is returning a Hash Table. Then the Select-Object is returning just the BuildNumber section you want, the BuildNumber property and it's value. You need to add the -ExpandProperty parameter to only get the value back, not the name/value pair.

    Get-WMIObject -Class Win32_OperatingSystem | Select-Object BuildNumber

Returns

    @{BuildNumber=7601}

With ExpandProperty

    Get-WMIObject -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber

Returns

    7601

OTHER TIPS

Just another option with a ping test to skip unavailable machines.

Get-Content .\Computers.txt | Where-Object {Test-Connection -ComputerName $_ -Count 1 -Quiet} | Foreach-Object {

    $sweet =  Get-WmiObject -Class Win32_OperatingSystem -ComputerName $_ | Select-Object -ExpandProperty BuildNumber

    New-Object PSObject -Property @{
        ComputerName = $_.__SERVER
        Sweet =  $sweet
        OS = if ($sweet -eq 7601) {'Yes!'} else {'Nooooo!'}    
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top