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.
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 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:
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.
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]::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.