The foreach statement.
syntax
Section titled “syntax”The foreach statement iterates of each object within a collection. In the example below, I’ve named the variables item, & collection to make it a little clearer. Do note, $item isn’t a real variable. The foreach loop automatically assigns an item to it from each item in the collection. Once finished, if you were to call $item, it’ll only return the last item stored there.
$collection = @(1,2,3,4,5)foreach ($item in collection){Write-host "$item is a number" #This pointlessly writes to the host 5 times. Each line prints the number, followed by the string.}Escaping the simplicity, we can observer a little more complex example of foreach.
$collection = @{ "cat" = "meowed" "dog" = "barked" "IT Admin" = "yelled" "The quiet man" = $null}foreach ($item in $collection.Keys){ # Runs through our list. All 3 items in our list are ran through one by one. Write-host "The $item $($collection.$item)" #Command to run on each item in the collection}The output in the terminal would be as follows: The IT Admin yelled The cat meowed The dog barked The Quiet man
To provide a more focused, IT administration version of this, you would use something similar to the below.
$WinFeature = Get-WindowsOptionalFeature -Online | Select-Object -Property FeatureName, Stateforeach ($Feature in $WinFeature) { if ($($Feature.state -eq 'Enabled', 'Enabled Pending')) { Write-Output "$Feature is currently $($Feature.State)" } elseif ($($Feature.state -eq 'Disabled', 'Disabled Pending')) { Write-Output "$Feature is currently $($Feature.State)" } else { Export-Csv -inputobject $Feature 'c:\Temp\otherfeaturestates.csv' -Append -NoTypeInformation }}Ok, I’ll admit. Intreating through Enabled/Disabled features isn’t exiting, and not something we’d realistically need to do. However… Perhaps you’d want to inetrate through a list of disabled AD users and remove user groups? Once you start building tools like that, and seeing how you can chaining them together, you’ll be near enough ready to automate yourself out of a job!