Powershell Journal – For Loop in a single statement

Recently I was given a task for writing a powershell script which does some DELETION of blob objects, but the challenge was to keep this script minimal and mostly limited to a one liner.

I know, you won’t call a one liner as a script, but instead a command.
So, I took this challenge and started dewlling into “How we can iterate over a list of objects in a single line with Powershell

Yes, I know its possible by just writing a the for loop syntax in a single line like this, but we are going to do it using pipe operator. So we cannot use a regular For Loop syntax in this case.

We can do it 2 ways.

Lets suppose, we are trying to list files in a directory

D:\Navin\test> Get-ChildItem .

    Directory: D:\Navin\test

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        8/27/2019   9:47 PM              0 test1 - Copy.txt
-a----        8/27/2019   9:47 PM              0 test1.txt
-a----        8/27/2019   9:47 PM              0 test2.txt
-a----        8/27/2019   9:47 PM              0 test3.txt

Based on the output, we can use ForEach-Object along with a pipeline operator here to pass the result of first command to second command as input. At the same time, you can refer to $_. as the current element of list, while iterating in loop.

D:\Navin\test> Get-ChildItem  | ForEach-Object {write-host $_.Name}
test1 - Copy.txt

Other way of doing this is by using a % symbol instead of ForEach-Object, this does exactly the same thing, but is a more shorter version.

D:\Navin\test> Get-ChildItem  | % {write-host $_.Name}
test1 - Copy.txt

That is how we can iterate over a result (list) in a single line of powershell.
Go ahead and explore this by yourself, you will be amazed to know, how easy it is.