PowerShell Welcome to this addition of the PowerShell ABC's where you'll find 26 posts detailing a component of the PowerShell scripting language, one letter at a time.  For today's letter of "V" I will talk about default statement output, and specifically voidable statements.

void01 In traditional programming languages, statements do not return a value.  Think of the C++ increment operator in the following statement: "a++;".  In this example the value of variable a is incremented by one.  The value of the variable a is not returned from this statement.  In fact, All C/C++/C# statements do not return values.  This is not true for PowerShell though.  In PowerShell, all statements return a value.

This caused a problem for the designers of PowerShell.  If all statements returned values, then this would lead to confusion for traditional programmers out there that were expecting the opposite behavior.  In fact, the increment (++) and decrement (--) operators were almost not included in PowerShell because of this issue.

In the early part of the PowerShell design, developers were confused by the fact that the the following code would produce the listed output.

for($i = 0; $i -lt 10; $i++) { }
1 2 3 4 5 6 7 8 9 10

The reason was that the "$i++" was returning the value of it's operation.  This was clearly not the desired result...

The designers of PowerShell came up with the concept of voidable statements.  This means that certain types of expressions, when used as statements, do not return values.  Voidable statements include assignments and the increment and decrement operators.  When they are used in an expression, they return a value, but when they are used as a standalone statement, they return no value.

If you want to explicitly discard the output of the statement, then you can use the type literal of [void] as a cast for your statement.  Another option is to use the redirection operator to redirect the output to the $null variable.  The following examples illustrate how to force a statement to be voidable.

PS C:\> Write-Output "hi"
PS C:\> [void](Write-Output "hi")
PS C:\> Write-Output "hi" > $null
PS C:\>

Voidable statements are not likely something you'll need to worry about and they won't likely effect the way you use PowerShell as they are designed to behave as you would expect a language to work.