The Community Book of Powershell Practices Master by Powershell.org - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

18. PIPE-01 Avoid using pipelines in scripts

Consider this:

Get-Content computer-names.txt | ForEach-Object -Process {  Get-WmiObject -Class Win32\_BIOS -ComputerName $\_ }

And now this alternative:

````

$computers = Get-Content computer-names.txt

foreach ($computer in $computers) {

Get-WmiObject -Class Win32_BIOS -ComputerName $computer

}````

The world definitely prefers the latter approach in a script or function.

Constructs offer far more flexibility, especially when you’re looping through multiple commands. Error handling becomes far easier and more structured with the latter approach, as does debugging.

Constructs often exhibit higher performance than pipeline-only approaches, but not always - it’s worth testing if you are dealing with large data-sets and if you’re in a context where performance matters. See PERF-02 for more detail on this.

On the command-line, by yourself, do whichever you prefer. It’s as you move into a script - an inherently more structured environment - that you want to start shifting to a more programming-style approach.

One-Liners

img1.pngimg2.jpgimg1.png In the context of the Scripting Games, if you are asked to do something as a “one-liner,” that means a single, continuous pipeline. Using semicolons to jam multiple “lines” into a single “line” does not count.If someone is asking for a one-liner, they’re doing it to test a certain type of PowerShell mettle. Mashing multiple lines together by means of semicolons does not fulfill the intent of the question. img1.pngimg1.pngimg3.pngimg1.pngimg3.pngimg1.png