Is and As: Working with Types

I recently spent some time helping a couple of former students figure out two PowerShell operators that they hadn't used before: -is and -as.

First, you have to understand that PowerShell keeps track of the type of object contained in a variable. The -is operator is simply designed to tell you whether or not a variable contains a certain type of object. For example:

$var = "500"

Does $var contain a number or a string? You might guess "string," but only -is can tell you for sure:

$var -is [string]
True

Notice that the data type is always enclosed in [brackets]. The -as operator also deals with object types, but much more actively. It's designed to convert things to a particular type. For example, suppose I want to display the amount of free space, in megabytes, on my computer's fixed disks:

Get-WmiObject -class Win32_LogicalDisk -filter "DriveType=3" |
Select-Object -property DeviceID,@{label='FreeSpace(MB)';expression={$_.FreeSpace / 1MB}}

Try it - it does the trick, but it displays the free space with a large fractional component. What I really want is to convert that floating-point number to an integer, either rounding it up or down or even just dropping the fraction (for this purpose, I'm not picky). The -as operator does that:

Get-WmiObject -class Win32_LogicalDisk -filter "DriveType=3" |
Select-Object -property DeviceID,@{label='FreeSpace(MB)';expression={$_.FreeSpace / 1MB -as [int]}}

And it turns out it properly rounds the result, too! These are both useful tricks to have up your sleeve. So much so, in fact, that I'm adding them to my classes from now on, and I'm going to make sure they're mentioned in the PowerShell book I'm working on. 

Are there any other PowerShell operators you've seen, but aren't sure about how to use? Let me know - I'll write up an article.

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) ×