r/PowerShell • • Dec 07 '19

PowerShell Traps - Collection of PowerShell traps and oddities

https://github.com/nightroman/PowerShellTraps
118 Upvotes

8 comments sorted by

View all comments

16

u/jsiii2010 Dec 08 '19 edited Dec 08 '19

You don't need @() to create arrays:

$array = 1,2,3

Anonymous functions:

& { param ($message) "the message is $message" } 'hi'

the message is hi

triple scriptblock foreach-object:

dir | foreach { $sum = 0 } { $sum++ } { "the sum is $sum" }

the sum is 511

Combining multiple statements into one pipeline with $(). Also a less often used version of foreach-object.

$( echo hi; echo there ) | measure | foreach count

2

Using assembly and namespace and popping open a dialog box:

using assembly System.Windows.Forms
using namespace System.Windows.Forms
[messagebox]::show('hello world')

This is annoying. Passing an array to start-job (or start-threadjob in PS 6). You have to add (, ) to the -argumentlist.

start-job { param ($var) $var.count } -argumentlist (,(1,2,3)) | receive-job -wait -auto

3

This is a nice way to pipe from foreach () without defining a function, and you don't have to use a lot of memory or wait for it to finish:

& { foreach ($i in 1..5) { $i } } | measure

There's actually two kinds of exceptions in powershell, command-terminating (usually pipeline terminating) and script-terminating. After the 2nd script-terminating exception from "throw", you don't get the 'hi' that follows. Both of these would work with try/catch.

1/0; 'hi'

Attempted to divide by zero.
At line:1 char:1
+ 1/0; 'hi'
+ ~~~
+ CategoryInfo          : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException
 
hi


throw; 'hi'

ScriptHalted
At line:1 char:1
+ throw; 'hi'
+ ~~~~~
+ CategoryInfo          : OperationStopped: (:) [], RuntimeException
+ FullyQualifiedErrorId : ScriptHalted

Oh, I didn't realize there was a link, lol.