FAQ PowerShell - Foreach vs Foreach-Object

Опубликовано: 02 Октябрь 2024
на канале: PDQ
5,547
113

Here is a basic overview of the difference between Foreach and Foreach-Object:

Foreach-Object works at the pipeline and processes each object one at a time. The variable you use to access the object in the pipeline is $_ or $PSItem (If you use PowerShell V3+) You also have the ability to add Begin and End scriptblocks to run commands before and after you process each object in the pipeline.

Foreach loads all objects of a collection into memory at once and then processes them.


Note: I didn't call out that Foreach-Object itself has an alias called foreach that can be used while in the pipeline. But alas, I did not remember that until after the video was published.


Can't get enough PDQ? Commence stalking in 3... 2... 1...
Twitter:
- General info: @admarsenal
- All things PDQ Deploy: @pdqdeploy
- All things PDQ Inventory: @pdqinventory
- Package Library updates: @packagelibrary
- Alerts and Technical updates@pdqalerts
Facebook:   / pdqlive  
Reddit:   / pdqdeploy  
LinkedIn:   / 17961724  
Our blog: https://www.pdq.com/blog/