Powershell Code

Kelly Garcia
Kelly Garcia used Ask the Experts™
on
Hi All,

I am trying to understand the code below. The foreach - what exactly is it looping through???

 $data = Get-WmiObject -Class Win32_OperatingSystem |  ForEach {
        New-Object PSObject -Property @{
            Computername = $env:computername
            OS = $_.Caption
            Version = $_.Version
            SystemDirectory = $_.systemdirectory
            Serialnumber = $_.serialnumber
            InstalledOn = ($_.ConvertToDateTime($_.InstallDate))            
            LastReboot = ($_.ConvertToDateTime($_.LastBootUpTime))            
        }

Open in new window


Regards,
K
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
That doesn't make any sense.  Try this instead:

Get-WmiObject -Class Win32_OperatingSystem | ForEach-Object -Process {
  [array]$object += New-Object -TypeName PSObject -Property @{
    Computername = $env:computername
    OS = $_.Caption
    Version = $_.Version
    SystemDirectory = $_.systemdirectory
    Serialnumber = $_.serialnumber
    InstalledOn = ($_.ConvertToDateTime($_.InstallDate))            
    LastReboot = ($_.ConvertToDateTime($_.LastBootUpTime))            
  }
}

Open in new window

PowerShell Developer
Top Expert 2010
Commented:
It makes perfect sense. It's looping through the result of get-WmiObject, which, in this case is a bit pointless because there's one object to "loop" through.

You could replace it with the more modern Get-CimInstance (Get-WmiObject is deprecated).
Get-CimInstance Win32_OperatingSystem | Select-Object @{n='ComputerName';e={ $env:COMPUTERNAME }}, @{Name='OS';Expression={ $_.Caption }}, Version, SystemDirectory, SerialNumber, InstallDate, LastBootUpTime

Open in new window

Qlemo"Batchelor", Developer and EE Topic Advisor
Top Expert 2015

Commented:
The important part is that you do not read it like this
($data = Get-WMIObject ...) | foreach { ... }

Open in new window

but
$data = ( Get-WMIObject ...) | foreach { ... } )

Open in new window

i.e. the expression including pipeline is executed, and the result assigned to the var.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial