Ever had a script which contains an array and a foreach loop? And then you want to test the content of the foreach, but only with one entry for troubleshooting purposes for example. I have. Lets paint an example.

$PossibleDrinks = @(
    "Coffee",
    "Milkshake",
    "Soda"
)

Foreach ($Drink in $PossibleDrinks) {
    Write-Output "I like to drink $Drink. Do you too?"
}

then I used to do something like:

## Get one entry
$Drink = $PossibleDrinks[0]

## Execute the content of the foreach
Write-Output "I like to drink $Drink. Do you too?"

This works fine, but I had to write the code to get the single entry and I’m lazy. Like every admin, am I right? So I wanted a quicker way.

## Get one entry
Foreach ($Drink in $PossibleDrinks) {}

## Execute the content of the foreach
Write-Output "I like to drink $Drink. Do you too?"

This way I can just copy the Foreach line and just add a “}” to the end. This saved me lots of time (cumulative) while troubleshooting my code.

Leave a Reply

Your email address will not be published. Required fields are marked *