Crossing the .NET Bridge

Crossing the .NET Bridge in PowerShell: PowerShell is an abstraction over the .NET framework.

PowerShell is an abstraction over the .NET framework. When Cmdlets don't exist, you can literally invoke raw C# code or instantiate massive .NET objects natively.

Instantiating .NET Classes

# Create a robust .NET Stopwatch instance specifically
$timer = New-Object -TypeName System.Diagnostics.Stopwatch
$timer.Start()
Start-Sleep -Seconds 2
$timer.Stop()

Write-Output "Elapsed Ms: $($timer.ElapsedMilliseconds)"

# Using Static .NET Methods utilizing the [ClassName]::Method syntax
$randomNum = [System.Math]::Round(4.567, 1)  # 4.6
$currentDate = [System.DateTime]::Now

Adding Raw C# Types

If truly desperate for performance or specific Windows API access, you can compile and embed C# directly into the pipeline!

$csharpCode = @"
public class MathHelper {
    public static int Add(int a, int b) {
        return a + b;
    }
}
"@

# Compiles the C# into the running PowerShell session!
Add-Type -TypeDefinition $csharpCode

# Utilize it!
[MathHelper]::Add(50, 25)  # 75