Technical Articles
F5 SMEs share good practice.
Showing results for 
Search instead for 
Did you mean: 
Custom Alert Banner

0151T000003d4aGQAQ.jpg 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.

0151T000003d4aHQAQ.jpg 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.

Thanks Mike, it was a great learning experience for me to force myself to pick a term of a specific letter for each post. I guess since I included the [void] cast, I should have included Out-Null as well. Oh well, maybe next round... B-)



BTW, not sure if you caught it or not, but I did a guest spot on Hal and Jon's PowerScripting Podcast Episode 61 where I talked about this series of posts:



Version history
Last update:
‎23-Jan-2009 07:12
Updated by: