Avatar of Kelly Garcia
Kelly Garcia
Flag for United Kingdom of Great Britain and Northern Ireland asked on

Powershell Code

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
PowershellScripting LanguagesWindows OS

Avatar of undefined
Last Comment
Qlemo

8/22/2022 - Mon
Jason Crawford

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

ASKER CERTIFIED SOLUTION
Chris Dent

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Qlemo

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.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck