PowerShell for Windows Admins

Aug 2 2011   9:02AM GMT

Using enums

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Following on my post about using enums http://msmvps.com/blogs/richardsiddaway/archive/2011/08/02/enums.aspx

I thought it might be fun to see how we can make our own.

If we look at Win32_LogicalDisk

PS > Get-WmiObject Win32_LogicalDisk | ft DeviceID, DriveType -a

DeviceID DriveType
——– ———
C:               3
E:               5
F:               5

Now I know that type 3 is a hard drive and type 5 is a CD/DVD but we want to see it in the code. Up to now I’ve used hash tables

$dt = DATA {            
ConvertFrom-StringData -StringData @'
0 = Unknown
2 = Removable Disk 
3 = Local Disk
4 = Network Drive
5 = Compact Disk
6 = RAM Disk
'@            
}             
Get-WmiObject Win32_LogicalDisk |             
select DeviceID,             
@{N="DiskType"; E={$dt["$($_.DriveType)"]}} |            
Format-Table -a

Create a hash table and then use a calculated field to perform the lookup

An alternative is to use an enumeration

Add-Type @"
public enum DiskType : int {
Unknown = 0,
RemovableDisk = 2, 
LocalDisk = 3,
NetworkDrive = 4,
CompactDisk = 5,
RAMDisk = 6 
}
"@            
             
Get-WmiObject Win32_LogicalDisk |             
select DeviceID,             
@{N="DiskType"; E={[disktype]($($_.DriveType))}} |            
Format-Table -a

Notice that the order of values is reversed between the hash table and the enum.

The lookup syntax is slightly easier but the code to set it up is slightly harder. We also need to make sure there aren’t any spaces in the values we are defining.

Hash table or enum which do you want to use? Either give us the answer and both are relatively easy to implement.  It is possible to define multiple enums in one call to Add-Type

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: