We help IT Professionals succeed at work.

Powershell Code

201 Views
1 Endorsement
Last Modified: 2017-04-06
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

Jason CrawfordTransport Ninja
CERTIFIED EXPERT

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
CERTIFIED EXPERT
Top Expert 2010
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION
Qlemo"Batchelor", Developer and EE Topic Advisor
CERTIFIED EXPERT
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.