Link to home
Start Free TrialLog in
Avatar of Kelly Garcia
Kelly GarciaFlag 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
Avatar of Jason Crawford
Jason Crawford
Flag of United States of America image

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
Avatar of Chris Dent
Chris Dent
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.