Skip to content
AgileLogics
5 min read

Using .NET Directly

Prerequisites: Classes

Everything in PowerShell is .NET underneath, and the whole .NET class library is available when no cmdlet does what you need.

Static members and constructors

[math]::Max(3, 9)
[guid]::NewGuid().ToString().Length
[System.IO.Path]::GetFileNameWithoutExtension('C:\data\report.final.pdf')
[string]::IsNullOrWhiteSpace('   ')
[int]::TryParse('42', [ref]$null)

$builder = [System.Text.StringBuilder]::new()
[void]$builder.Append('Power')
[void]$builder.Append('Shell')
$builder.ToString()
9
36
report.final
True
True
PowerShell
  • [Type]::Member calls a static method or property.
  • [Type]::new(...) creates an instance.
  • [void] discards a method's return value (like | Out-Null, but faster).
  • The System. prefix is optional: [IO.Path] works too.

Generic collections

$seen = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
foreach ($name in 'Ada', 'ada', 'Linus', 'ADA') {
  if ($seen.Add($name)) { "new: $name" } else { "duplicate: $name" }
}

$queue = [System.Collections.Generic.Queue[int]]::new()
1..3 | ForEach-Object { $queue.Enqueue($_) }
$queue.Dequeue()
$queue.Count

$prices = [System.Collections.Generic.Dictionary[string, decimal]]::new()
$prices['coffee'] = 3.5
$prices.TryGetValue('tea', [ref]$null)
new: Ada
duplicate: ada
new: Linus
duplicate: ADA
1
2
False

List[T], HashSet[T], Dictionary[K,V], Queue[T], and Stack[T] are typed and fast — use them for large data sets in performance-sensitive scripts.

[ref] parameters

Some .NET methods return extra values through out parameters. Pass a variable with [ref]:

$number = 0
if ([int]::TryParse('123', [ref]$number)) { "Parsed: $($number + 1)" }
if (-not [int]::TryParse('abc', [ref]$number)) { 'Not a number' }
Parsed: 124
Not a number

Hashing and encoding

$bytes = [System.Text.Encoding]::UTF8.GetBytes('hello')
[Convert]::ToBase64String($bytes)
[System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('aGVsbG8='))
$sha = [System.Security.Cryptography.SHA256]::HashData($bytes)
[Convert]::ToHexString($sha).ToLower()
aGVsbG8=
hello
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

For files, the Get-FileHash cmdlet is simpler. Compare against the Hash Generator and Base64 Encoder.

Loading assemblies and C#

Add-Type -AssemblyName System.Web loads a .NET assembly; Add-Type -TypeDefinition '...C# code...' compiles C# on the fly — useful for performance-critical code or calling Windows APIs.