Using Enums in PowerShell

Frequently, objects in .NET will use enums in their methods or constructors. Because of this it's important to understand how to reference an enum in PowerShell. Commonly used types like StreamReader, DateTime, and StreamWriter are examples of types that have constructors with enums. Referencing an enum in PowerShell is similar to the synax used when calling a static method on an object.

Referencing an Enum in a Method Call

A common .NET type that has an overload with an enum is "DateTime". When creating a DateTime object you can specify the "DateTimeKind" where "DateTimeKind" is either Local, Unspecified, or Utc. Lets take a look at how you can create an instance of a DateTime object using the constructor that takes a DateTimeKind enum:

 # Create a UTC DateTime object
 $date = New-Object -TypeName DateTime -ArgumentList 2013,11,23,5,30,0,([System.DateTimeKind]::UTC)

 # List properties of the new object
 $date | Format-List -Force

 Date        : 11/23/2013 12:00:00 AM
 Day         : 23
 DayOfWeek   : Saturday
 DayOfYear   : 327
 Hour        : 5
 Kind        : Utc
 Millisecond : 0
 Minute      : 30
 Month       : 11
 Second      : 0
 Ticks       : 635207814000000000
 TimeOfDay   : 05:30:00
 Year        : 2013
 DateTime    : Saturday, November 23, 2013 5:30:00 AM


As you can see, the Kind property has a value of Utc. In most cases you will be referencing enums when accessing functionality through an API or assembly that is not expose its methods through a PowerShell cmdlet. The same square bracket notation is also used when referencing an enum when calling a method.

© 2024