Shuzheng
Shuzheng

Reputation: 13840

Why pipe to %{0} in PowerShell?

PowerShell scripts sometimes pipe to %{0}:

[byte[]]$bytes = 0..65535 | %{0};

I know % is an alias for ForEach-Object and $_ represents the current pipeline object.

Is this solely to avoid output? Isn’t there a smarter way of doing it?

Upvotes: 1

Views: 2070

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

The pipeline on the right-hand side simply outputs the integer 0 65536 times - which when cast to byte[] produces a byte array of length 65536 with all values initialized to 0.

You could also have done:

[byte[]]$bytes = ,0 * 65536

As PetSerAl hints at, this is unnecessary since arrays of numerical value types initialize all items to 0 anyways, meaning that simply creating a new array, like so:

# using the new constructor keyword, PowerShell version > 5, 
[byte[]]$bytes = [byte[]]::new(65536)
# using New-Object, PowerShell version > 2
[byte[]]$bytes = New-Object 'byte[]' 65536

would also have given you the exact same result

Upvotes: 2

Related Questions