0

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

}
}
Matt Busche
  • 14,216
  • 5
  • 36
  • 61
Astirian
  • 63
  • 1
  • 10
  • Got it! Kinda... `$ErrorActionPreference = "SilentlyContinue" $Machines = Get-Content .\Computers.txt Foreach($Machine in $Machines) {Get-WmiObject -Class Win32_OperatingSystem -computer $Machine | Select-Object BuildNumber,@{Label="OS";Expression={If ($_.BuildNumber -eq "7601") {"Yes!"} else {"Nooooo!"}} } }` Now I only need to figure out how to tack that onto my PSObject. – Astirian Mar 01 '13 at 03:42
  • Please wait a bit and post it as an answer to your own question. – JPBlanc Mar 01 '13 at 04:37

2 Answers2

2

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
Schlauge
  • 483
  • 1
  • 4
  • 7
1

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!'}    
    }

}
Shay Levy
  • 121,444
  • 32
  • 184
  • 206