Into the [void]

Got an e-mail from a reader last night asking what the heck [void] was all about. He sent this example:

[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')

Wow, revenge of the square brackets, right? Typically, PowerShell uses square brackets for only two things: In an array index ($services[0]) and to denote a data type. In this case, both sets of square brackets are being used to denote data types. The first set, [void], are being used to cast a result. A simpler example of casting might look like this:

[int]$result = read-host "Enter a number"

By casting $result as an [int], or integer, we're ensuring that it won't contain a string like "hello." If the user enters a string that contains only digits, like "100," then the shell will convert that to an actual numeric object. So in the first example, the result of [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') is being cast as the data type [void]. Why? Well, normally that command would result in a success indication, and it tends to mess up a script's output. You don't want little status messages being spewed out. [void] is a way to suppress them. Casting anything as [void] basically makes it go away (I've been trying to cast the in-laws as [void] for years now), so that example is essentially taking the result of the command and discarding it. 

This is actually a very C#-flavored trick. A somewhat more "PowerShell way" to do it would be to take the result and pipe it to Out-Null:

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null

Same effect, but it uses PowerShell's pipeline a bit more naturally, I think.

Discuss this Blog Entry 1

Bewc (not verified)
on Oct 20, 2010
I liked your explanation, thanks!

Please or Register to post comments.

What's PowerShell with a Purpose Blog?

Don Jones demystifies Windows PowerShell.

Blog Archive

Sponsored Introduction Continue on to (or wait seconds) ×