- Courses
- 💻Programming Languages
- 🪟PowerShell
- Scripting Fundamentals
- Variables & Types
- Type Accelerators
On this page
PowerShell Type Accelerators
Published on June 10, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Type accelerators are short aliases for .NET type names. Instead of writing [System.Collections.Specialized.OrderedDictionary], you write [ordered]. Instead of [System.Text.RegularExpressions.Regex], you write [regex]. They appear in square brackets and can be used to cast values, constrain variable types, call static methods, and declare parameter attributes in functions. This lesson covers every practical use of type accelerators, how to discover the full list at runtime, and how to define your own.
Why Type Accelerators Exist
PowerShell is built on .NET. Every value in a PowerShell session is a .NET object, and many useful .NET types have long fully qualified names:
[System.Collections.Generic.List[string]]
[System.Text.RegularExpressions.Regex]
[System.Management.Automation.PSCredential]
[System.Collections.Specialized.OrderedDictionary]
Type accelerators map these to short, memorable names:
[list[string]]
[regex]
[pscredential]
[ordered]
The two forms are completely equivalent. Type accelerator names are case-insensitive — [Int], [INT], and [int] all refer to the same type.
Three Ways to Use Type Accelerators
Casting a value
A cast converts a value from one type to another. Place the type accelerator immediately before the value:
[int]"42" # string → integer: 42
[string]3.14 # number → string: "3.14"
[bool]0 # number → boolean: False
[bool]1 # number → boolean: True
[bool]"" # empty string → boolean: False
[bool]"hi" # non-empty string → boolean: True
[datetime]"2024-06-15" # string → DateTime object
[double]"3.14159" # string → double-precision float
If the conversion is not possible, PowerShell throws an error:
[int]"hello" # Cannot convert value "hello" to type "System.Int32"
Constraining a variable type
Place the type accelerator before the variable name at assignment time. The variable then only accepts values of that type — PowerShell converts compatible values automatically and throws an error for incompatible ones:
[int]$count = 10
$count = "20" # converted to integer 20 automatically
$count = "abc" # error — cannot convert
[datetime]$deadline = "2025-12-31"
$deadline = "2024-01-01" # converted to DateTime automatically
[string]$name = 42 # converted to "42"
Constrained variables are useful in calculations where accidental type coercion could produce wrong results.
Calling static methods
Many .NET types expose static methods — class-level functions that do not require an instance. Call them with :: after the type accelerator:
[datetime]::Now # current date and time
[datetime]::UtcNow # current UTC date and time
[guid]::NewGuid() # generate a new GUID
[math]::Round(3.14159, 2) # round to 2 decimal places → 3.14
[math]::Abs(-42) # absolute value → 42
[math]::Sqrt(144) # square root → 12
[string]::IsNullOrEmpty("") # True
[string]::IsNullOrWhiteSpace(" ") # True
Numeric Type Accelerators
PowerShell has accelerators for every common .NET numeric type:
AcceleratorFull typeRange / notes[byte]``System.Byte0 to 255[int] / [int32]``System.Int32-2,147,483,648 to 2,147,483,647[int16]``System.Int16-32,768 to 32,767[int64] / [long]``System.Int64±9.2 × 10¹⁸[float]``System.SingleSingle-precision decimal[double]``System.DoubleDouble-precision decimal (default for decimals)[decimal]``System.DecimalHigh precision, no floating-point rounding errors[bigint]``System.Numerics.BigIntegerArbitrarily large integers
[int]$x = 5
[double]$y = 3.14159
[decimal]$price = 19.99 # use for money — no floating-point errors
# BigInteger for numbers that exceed int64
[bigint]$factorial = [bigint]::Pow(2, 100)
$factorial.ToString()
# 1267650600228229401496703205376
String and Date Accelerators
[string]$name = "Alice"
[char]$letter = 'A' # single character
[char]65 # 'A' — ASCII code to character
[datetime]$now = [datetime]::Now
[datetime]$date = "2025-07-04" # parses from ISO 8601 string
$date.DayOfWeek # Friday
$date.Year # 2025
[timespan]$duration = [timespan]::FromHours(2.5)
$duration.TotalMinutes # 150
$duration.ToString() # 02:30:00
# Timespan arithmetic
$start = [datetime]"2025-01-01"
$end = [datetime]"2025-12-31"
($end - $start).Days # 364
Collection Type Accelerators
# Ordered dictionary — preserves insertion order (unlike hashtable)
$config = [ordered]@{
Server = "prod-01"
Port = 8080
Timeout = 30
}
$config.Keys # Server, Port, Timeout — always in this order
# Typed generic list — supports Add, Remove, Sort, Contains natively
$names = [System.Collections.Generic.List[string]]::new()
$names.Add("Alice")
$names.Add("Bob")
$names.Add("Charlie")
$names.Remove("Bob")
$names.Count # 2
# Short alias for the same type
$numbers = [list[int]]::new()
$numbers.Add(10)
$numbers.Add(20)
$numbers.Add(30)
$numbers | Sort-Object # 10, 20, 30
# Hashtable
$lookup = [hashtable]@{ "key1" = "value1"; "key2" = "value2" }
Network and Identity Accelerators
# IP address parsing and validation
[ipaddress]"192.168.1.100" # creates a System.Net.IPAddress object
([ipaddress]"192.168.1.100").AddressFamily # InterNetwork (IPv4)
([ipaddress]"::1").AddressFamily # InterNetworkV6 (IPv6)
# Validate an IP address string safely
try { [ipaddress]"not.an.ip" } catch { "Invalid IP address" }
# Email address parsing
[mailaddress]"[email protected]"
([mailaddress]"Alice Smith <[email protected]>").DisplayName # Alice Smith
([mailaddress]"[email protected]").Host # example.com
# GUID generation and parsing
$id = [guid]::NewGuid()
$id.ToString() # e.g. "a3b4c5d6-e7f8-..."
[guid]"a3b4c5d6-e7f8-..." # parse an existing GUID string
The [regex] Accelerator
# Test whether a string matches a pattern
[regex]::IsMatch("hello123", "\d+") # True — contains digits
[regex]::IsMatch("hello", "^\d+$") # False — no digits
# Find the first match
$match = [regex]::Match("Server: prod-01", "prod-\d+")
$match.Value # prod-01
# Find all matches
$text = "Errors: 42 warnings and 7 critical issues"
$matches = [regex]::Matches($text, "\d+")
$matches | ForEach-Object { $_.Value } # 42, 7
# Replace with a pattern
[regex]::Replace("Hello World", "\s+", "_") # Hello_World
# Using the -match operator (simpler for single matches)
"[email protected]" -match "^[\w.]+@[\w.]+\.[a-z]{2,}$" # True
$Matches[0] # the full matched string
Attribute Type Accelerators for Functions
Several type accelerators are used specifically to decorate function parameters. These appear in param() blocks and are among the most frequently written type accelerators in production scripts:
function Invoke-Deploy {
[CmdletBinding(SupportsShouldProcess)]
[OutputType([string])]
param(
[Parameter(Mandatory, ValueFromPipeline)]
[Alias("Server", "Host")]
[ValidateNotNullOrEmpty()]
[string]$ComputerName,
[Parameter()]
[ValidateRange(1, 65535)]
[int]$Port = 443,
[Parameter()]
[pscredential]$Credential = [System.Management.Automation.PSCredential]::Empty
)
process {
if ($PSCmdlet.ShouldProcess($ComputerName, "Deploy")) {
"Deploying to $ComputerName on port $Port"
}
}
}
The attribute accelerators used here:
AcceleratorFull typePurpose[CmdletBinding]``CmdletBindingAttributeMakes function an advanced function[OutputType]``OutputTypeAttributeDeclares return type for IDE support[Parameter]``ParameterAttributeDeclares parameter metadata[Alias]``AliasAttributeAdds alternate parameter names[ValidateNotNullOrEmpty]``ValidateNotNullOrEmptyAttributeInput validation[ValidateRange]``ValidateRangeAttributeNumeric range validation[pscredential]``PSCredentialSecure credential parameter type
The -is and -as Operators
Type accelerator names work as strings with the -is and -as comparison operators:
# -is tests whether a value is of a given type
42 -is 'int' # True
"hi" -is 'string' # True
3.14 -is 'double' # True
42 -is [int] # also True — both forms work
# -as attempts a conversion, returns $null instead of throwing on failure
"42" -as [int] # 42
"hello" -as [int] # $null (no error thrown)
"2024-01-01" -as [datetime] # DateTime object
# Safe conversion pattern — check for null after -as
$value = $input -as [int]
if ($null -eq $value) {
Write-Error "Input is not a valid integer"
}
-as is safer than a direct cast in input-handling code because it never throws — it returns $null when conversion fails.
Discovering All Available Type Accelerators
The complete list of type accelerators is stored in a non-public .NET class inside the PowerShell assembly. Access it through reflection:
# Get all type accelerators as a hashtable
$accelerators = [psobject].Assembly.GetType(
'System.Management.Automation.TypeAccelerators'
)::Get
# Display them sorted alphabetically
$accelerators.GetEnumerator() |
Sort-Object Key |
Format-Table @{ Name = "Accelerator"; Expression = { "[$($_.Key)]" } },
@{ Name = "Full Type"; Expression = { $_.Value.FullName } }
Search for a specific type by name:
# Find accelerators whose short name contains "credential"
$accelerators.GetEnumerator() |
Where-Object Key -like "*credential*" |
Select-Object Key, Value
# Find the accelerator for a known full type name
$accelerators.GetEnumerator() |
Where-Object { $_.Value.FullName -like "*Regex*" } |
Select-Object Key, Value
Count the total number of built-in accelerators:
$accelerators.Count # typically 80+ depending on PowerShell version
Creating Custom Type Accelerators
You can add your own type accelerators to the session using the same reflection-based access. Custom accelerators are available for the duration of the current session and are not persisted across sessions unless you add them to a profile or module:
$acceleratorType = [psobject].Assembly.GetType(
'System.Management.Automation.TypeAccelerators'
)
# Add a custom type accelerator
$acceleratorType::Add('WebClient', [System.Net.WebClient])
# Now use it like any built-in accelerator
$client = [WebClient]::new()
$html = $client.DownloadString("https://example.com")
# Add an accelerator for a custom class loaded via Add-Type
Add-Type -TypeDefinition @"
public class Point {
public int X;
public int Y;
public Point(int x, int y) { X = x; Y = y; }
}
"@
$acceleratorType::Add('Point', [Point])
$p = [Point]::new(10, 20)
$p.X # 10
Removing custom type accelerators
$acceleratorType::Remove('WebClient')
$acceleratorType::Remove('Point')
Only custom-added accelerators can be removed. Attempting to remove a built-in accelerator succeeds silently but the built-in is restored on the next PowerShell session.
Custom accelerators persist only for the current session. To make them available in every session, add the
Addcalls to your$PROFILEscript or export them from a module using the module'sScriptsToProcessentry.
Practical Examples
Ensure numeric arithmetic instead of string concatenation
$a = "5"
$b = "7"
$a + $b # "57" — string concatenation
[int]$a = "5"
[int]$b = "7"
$a + $b # 12 — integer addition
Parse a date from user input safely
$input = Read-Host "Enter a date (yyyy-MM-dd)"
$date = $input -as [datetime]
if ($null -eq $date) {
Write-Error "Invalid date format"
} else {
"Parsed: $($date.ToString('D'))"
}
Generate and validate GUIDs
# Generate a new GUID
$id = [guid]::NewGuid().ToString()
# Validate whether a string is a valid GUID
function Test-Guid {
param([string]$Value)
$null -ne ($Value -as [guid])
}
Test-Guid "not-a-guid" # False
Test-Guid "a3b4c5d6-e7f8-1234-abcd-ef0123456789" # True
Working with IP addresses in network scripts
function Test-ValidIPAddress {
param([string]$Address)
$null -ne ($Address -as [ipaddress])
}
Test-ValidIPAddress "192.168.1.1" # True
Test-ValidIPAddress "999.999.1.1" # False
Test-ValidIPAddress "::1" # True (valid IPv6)
Common Type Accelerators: Quick Reference
AcceleratorFull .NET typeCommon use[int] / [int32]``System.Int32Integer arithmetic[long] / [int64]``System.Int64Large integers[double]``System.DoubleFloating-point math[decimal]``System.DecimalFinancial calculations[bigint]``System.Numerics.BigIntegerArbitrarily large numbers[string]``System.StringText[char]``System.CharSingle character[bool]``System.BooleanTrue/False[datetime]``System.DateTimeDates and times[timespan]``System.TimeSpanDurations and intervals[guid]``System.GuidUnique identifiers[regex]``System.Text.RegularExpressions.RegexPattern matching[ipaddress]``System.Net.IPAddressIP address parsing[mailaddress]``System.Net.Mail.MailAddressEmail address parsing[pscredential]``System.Management.Automation.PSCredentialStored credentials[pscustomobject]``System.Management.Automation.PSObjectCustom objects[hashtable]``System.Collections.HashtableKey-value collections[ordered]``System.Collections.Specialized.OrderedDictionaryOrder-preserving dictionary[array]``System.ArrayArray operations
Common Mistakes to Avoid
Using [int] for financial or scientific calculations. Integers truncate decimal values silently. [int]2.9 returns 3 (rounded, not truncated). Use [decimal] for money and [double] or [decimal] for precise scientific values.
Casting directly instead of using -as for user input. A direct cast like [int]$userInput throws a terminating error when the input is not convertible. Use $userInput -as [int] and check for $null to handle invalid input gracefully.
Assuming custom type accelerators persist between sessions. They exist only in the current session. Add them to $PROFILE or a module if they are needed permanently.
Using [float] when you mean [double]. [float] maps to System.Single — 32-bit single-precision floating point. Most PowerShell numeric operations use [double] (64-bit). Using [float] can introduce precision loss in intermediate calculations.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Hash Tables
Next
Comparison and Logical Operators
-
Why Type Accelerators Exist
-
Three Ways to Use Type Accelerators
- Casting a value
- Constraining a variable type
- Calling static methods
-
Numeric Type Accelerators
-
String and Date Accelerators
-
Collection Type Accelerators
-
Network and Identity Accelerators
-
The
[regex]Accelerator -
Attribute Type Accelerators for Functions
-
The
-isand-asOperators -
Discovering All Available Type Accelerators
-
Creating Custom Type Accelerators
- Removing custom type accelerators
-
Practical Examples
- Ensure numeric arithmetic instead of string concatenation
- Parse a date from user input safely
- Generate and validate GUIDs
- Working with IP addresses in network scripts
-
Common Type Accelerators: Quick Reference
-
Common Mistakes to Avoid
