PowerShell_2 Welcome to this addition of the PowerShell ABC's where you'll find 26 posts detailing a component of the PowerShell scripting language, one letter at a time.  For today's letter of "T" I will talk about type specification and, in particular, Type Literals.

type If you've seen any example PowerShell scripts, you've likely seen some syntax that looks like [type].  This is referred to as a type literal.  In PowerShell, you can use type literals to specify a particular type for your operation.

Type literals can be used  in several ways.  They can be used as operators in a type cast, as part of a variable declaration, or as an object itself.

 

Casting

Casting involves the conversion of one type to another.  Let's say you have a string that contains a number and you would like to convert the native type of that variable to a number.  You can do so with the following cast:

PS C:\> $a = "123"
PS C:\> $a.GetType().Name
StringPS C:\> $i = [int]$a
PS C:\> $i.GetType().Name
Int32

Variable Declaration

Type literals can also be used to declare a variable of a specific type.  Variables in PowerShell are dynamic in nature, meaning that they can change types depending on the context in which they are used.  In some cases, you will want to be in more control of the type of your variables.  By prefixing them with a type literal, PowerShell will honor your type request and enforce that type on the specified variable.  In the above example, we casted a string to a integer with an explicit type literal cast.  This could have been done directly on the input string "123".  Or, you could have declared the variable $a to be of type int in it's variable declaration.

PS C:\> $a = [int]"123"
PS C:\> $a.GetType().Name
Int32
PS C:\> [int]$a = "123"
PS C:\> $a.GetType().Name
Int32

Object Representation and Static Member Access

In other situations, type literals can be used to access static methods in .NET classes.  Static methods are methods that do not require an instance of the object to be created before you can call them.  The System.DateTime class for instance has a static property Now() that will return the current date and time.  By appending double colons "::" to the type literal and then adding the static method name and parameters, you call that method.  In the following example, I'll pipe the type literal for DateTime into the Get-Member Cmdlet to list out all the static methods in the DateTime class:

PS C:\> [DateTime] | Get-Member -static 

   TypeName: System.DateTime

Name                  MemberType Definition
----                  ---------- ----------
Compare               Method     static System.Int32 Compare(DateTime t1, DateTime t2)
DaysInMonth           Method     static System.Int32 DaysInMonth(Int32 year, Int32 month)
Equals                Method     static System.Boolean Equals(DateTime t1, DateTime t2),...
FromBinary            Method     static System.DateTime FromBinary(Int64 dateData)
FromFileTime          Method     static System.DateTime FromFileTime(Int64 fileTime)
FromFileTimeUtc       Method     static System.DateTime FromFileTimeUtc(Int64 fileTime)
FromOADate            Method     static System.DateTime FromOADate(Double d)
get_Now               Method     static System.DateTime get_Now()
get_Today             Method     static System.DateTime get_Today()
get_UtcNow            Method     static System.DateTime get_UtcNow()
IsLeapYear            Method     static System.Boolean IsLeapYear(Int32 year)
op_Addition           Method     static System.DateTime op_Addition(DateTime d, TimeSpan t)
op_Equality           Method     static System.Boolean op_Equality(DateTime d1, DateTime d2)
op_GreaterThan        Method     static System.Boolean op_GreaterThan(DateTime t1, DateTime t2)
op_GreaterThanOrEqual Method     static System.Boolean op_GreaterThanOrEqual(DateTime t1,...
op_Inequality         Method     static System.Boolean op_Inequality(DateTime d1, DateTime d2)
op_LessThan           Method     static System.Boolean op_LessThan(DateTime t1, DateTime t2)
op_LessThanOrEqual    Method     static System.Boolean op_LessThanOrEqual(DateTime t1, DateTime t2)
op_Subtraction        Method     static System.DateTime op_Subtraction(DateTime d, TimeSpan t), ...
Parse                 Method     static System.DateTime Parse(String s), static System.DateTime ...
ParseExact            Method     static System.DateTime ParseExact(String s, String format, ...
ReferenceEquals       Method     static System.Boolean ReferenceEquals(Object objA, Object objB)
SpecifyKind           Method     static System.DateTime SpecifyKind(DateTime value, DateTimeKind kind)
TryParse              Method     static System.Boolean TryParse(String s, DateTime& result), static...
TryParseExact         Method     static System.Boolean TryParseExact(String s, String format, ...
MaxValue              Property   static System.DateTime MaxValue {get;set;}
MinValue              Property   static System.DateTime MinValue {get;set;}
Now                   Property   System.DateTime Now {get;}
Today                 Property   System.DateTime Today {get;}
UtcNow                Property   System.DateTime UtcNow {get;}

PS C:\> [DateTime]::Now
Tuesday January 20, 2009 9:50:29 AM

Type Name Aliases

You may have noticed the native types in the above examples such as "String" and "Int32".  PowerShell provides a set of type name aliases that are more in line with traditional programming languages that are aliases to the .NET framework types.  You are free to use the type name aliases or the native types in your type literal usage, both are equivalent.  The following table taken from Windows PowerShell in Action by Bruce Payette, lists out all the type name aliases and their native types.


PowerShell Type Alias|Corresponding .NET Type

[int]System.Int32
[int[]]System.Int32[]
[long]System.Int64
[long[]]System.Int64[]
[string]System.String
[string[]]System.String[]
[char]System.Char
[char[]]System.Char[]
[bool]System.Boolean
[bool[]]System.Boolean[]
[byte]System.Byte
[byte[]]System.Byte[]
[double]System.Double
[double[]]System.Double[]
[decimal]System.Decimal
[decimal[]]System.Decimal[]
[float]System.Single
[single]System.Single
[regex]System.Text.RegularExpression.Regex
[array]System.Array
[xml]System.Xml.XmlDocument
[scriptblock]System.Management.Automation.ScriptBlock
[switch]System.Management.Automation.SwitchParameter
[hashtable]System.Collections.Hashtable
[psobject]System.Management.Automation.PSObject
[type]System.Type
[type[]]System.Type[]