PowerShell with a Purpose Blog

Into the [void]

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


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.
Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.