The foreach statement is used to iterate through a collection.
foreach ($item in $collection) {
# do something to $item
}
Listing the active processes:
foreach ($i in Get-Process) {
$i.ProcessName
}
# hit enter 1 more time if you still see the >> prompt
You could simply pipe it to the foreach statement. Use the $_ variable to refer to the current item in the foreach loop.
Get-Process | foreach { $_.ProcessName }
Or you can check if the process is responding
foreach ($item in Get-Process) {
if ($item.Responding -eq "True"){
Write-Host $Item.Name
}
}
Listing processor information:
$strComputer = "."
$collectionItems = get-wmiobject -class "Win32_Processor" -namespace "root\CIMV2" `
-computername $strComputer
foreach ($objectItem in $collectionItems) {
write-host "Caption: " $objectItem.Caption
write-host "CPU Status: " $objectItem.CpuStatus
write-host "Current Clock Speed: " $objectItem.CurrentClockSpeed
write-host "Device ID: " $objectItem.DeviceID
write-host "L2 Cache Size: " $objectItem.L2CacheSize
write-host "L2 Cache Speed: " $objectItem.L2CacheSpeed
write-host "Name: " $objectItem.Name
write-host
}
Listing disk information:
$strComputer = "."
$collectionItems = get-wmiobject -class "Win32_DiskDrive" -namespace "root\CIMV2" `
-computername $strComputer
foreach ($objectItem in $collectionItems) {
write-host "Description: " $objectItem.Description
write-host "Device ID: " $objectItem.DeviceID
write-host "Interface Type: " $objectItem.InterfaceType
write-host "Media Type: " $objectItem.MediaType
write-host "Model: " $objectItem.Model
write-host "Partitions: " $objectItem.Partitions
write-host "Size: " $objectItem.Size
write-host "Status: " $objectItem.Status
write-host
}