On this page

Using .NET Classes Directly in PowerShell

Updated on June 25, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

PowerShell scripts that leverage .NET directly and avoid the pipeline tend to be significantly faster than idiomatic PowerShell. Cmdlets provide convenience, validation, and formatting, but they also introduce overhead—often 10x to 100x slower for operations like file reading. When performance matters, calling .NET classes and methods directly is the most effective optimization technique. However, many of these techniques reduce readability, so use them only when performance dictates.


Why .NET Classes Are Faster​

PowerShell is built on .NET, but cmdlets add layers of abstraction. Get-Content, for example, adds NoteProperties to every object it emits to improve pipeline compatibility, which introduces significant overhead. The .NET methods bypass this entirely.

Key reasons .NET is faster:

The difference is dramatic. Reading a 170,000-line file with Get-Content takes roughly 6 seconds, while [System.IO.File]::ReadAllLines() completes in 40-90 milliseconds—over 100x faster.


Accessing .NET Classes in PowerShell​

Syntax for Static Methods​

Use square brackets with the full namespace and class name, followed by :: and the method name:


[System.IO.Path]::GetFileNameWithoutExtension("C:\temp\file.log")

Code explanation: The [System.IO.Path] class is referenced inside square brackets. :: calls a static method. This returns the filename without the extension: "file".

Syntax for Instance Methods​

Create an object with New-Object or by calling a constructor, then call methods on the object:


$reader = New-Object System.IO.StreamReader("C:\temp\file.log")

$content = $reader.ReadToEnd()

$reader.Close()

Code explanation: New-Object creates an instance of StreamReader. The ReadToEnd() method reads the entire file as a string. Close() releases the file handle.

Type Accelerators​

PowerShell provides shortcuts for common .NET types:

Type AcceleratorFull .NET Type[string]``System.String``[int]``System.Int32``[datetime]``System.DateTime``[math]``System.Math``[io.file]``System.IO.File``[io.directory]``System.IO.Directory

Loading Additional Assemblies​

Some .NET classes require loading the assembly first. Use Add-Type -AssemblyName:


Add-Type -AssemblyName System.Linq

File and Directory Operations​

Reading Files​

Cmdlet.NET AlternativePerformance GainGet-Content``[System.IO.File]::ReadAllLines()~100x fasterGet-Content``[System.IO.File]::ReadAllText()~100x fasterGet-Content``[System.IO.StreamReader]~10-15x faster

Example: reading all lines


# Slow (idiomatic)

$lines = Get-Content "C:\temp\large.log"



# Fast (.NET)

$lines = [System.IO.File]::ReadAllLines("C:\temp\large.log")

Code explanation: ReadAllLines reads the entire file into a string array in one operation. Get-Content streams lines one at a time through the pipeline, adding overhead to each line.

Example: reading as a single string


# Slow

$content = Get-Content "C:\temp\file.txt" -Raw



# Fast

$content = [System.IO.File]::ReadAllText("C:\temp\file.txt")

Example: using StreamReader for fine control


$reader = [System.IO.StreamReader]::new("C:\temp\large.log")

while (($line = $reader.ReadLine()) -ne $null) {

    # Process line

}

$reader.Close()

Code explanation: StreamReader reads lines one at a time without the pipeline overhead. This is the fastest way to process large files line-by-line.

Writing Files​

Cmdlet.NET AlternativeSet-Content / Out-File``[System.IO.File]::WriteAllText()``Add-Content``[System.IO.File]::AppendAllText()


# Slow

"Hello World" | Out-File "C:\temp\output.txt"



# Fast

[System.IO.File]::WriteAllText("C:\temp\output.txt", "Hello World")

Listing Files​

Cmdlet.NET AlternativeKey DifferenceGet-ChildItem``[System.IO.Directory]::GetFiles()Returns strings, not objectsGet-ChildItem``[System.IO.Directory]::GetDirectories()Files onlyGet-ChildItem``[System.IO.Directory]::GetFileSystemEntries()Both files and directories


# Slow (returns FileInfo objects)

$files = Get-ChildItem "C:\Windows\System32" -File



# Fast (returns strings, no pipeline)

$files = [System.IO.Directory]::GetFiles("C:\Windows\System32")



# Even faster: enumeration (streams results)

$files = [System.IO.Directory]::EnumerateFiles("C:\Windows\System32")

Code explanation: GetFiles returns an array of strings (filenames), while Get-ChildItem returns rich FileInfo objects with dozens of properties. If you only need filenames, the .NET method is much faster.

Important differences:


String Operations​

String Replacement​

Cmdlet.NET AlternativePerformance Difference-replace (regex).Replace() (literal)Much faster


# Slow (regex, even for literal strings)

$result = "PowerShell" -replace "Shell", "Script"



# Fast (literal string replacement)

$result = "PowerShell".Replace("Shell", "Script")

Code explanation: -replace uses regular expressions, which are powerful but slower. .Replace() performs a simple literal string replacement, which is significantly faster when regex is not needed.

StringBuilder for Repeated Concatenation​

Strings in .NET are immutable—each concatenation creates a new string. StringBuilder is specialized for building strings efficiently.


# Slow: creates a new string for each iteration

$result = ""

foreach ($i in 1..10000) {

    $result += "Item $i "

}



# Fast: appends in place

$sb = [System.Text.StringBuilder]::new()

foreach ($i in 1..10000) {

    $null = $sb.Append("Item $i ")

}

$result = $sb.ToString()

Code explanation: The += operator creates a new string each time, copying the entire accumulated content. StringBuilder maintains a mutable buffer and only creates the final string at the end.

Checking Strings​


# These are already .NET methods, no change needed

"Hello".StartsWith("He")      # True

"Hello".Contains("ell")       # True

"Hello".ToUpper()             # "HELLO"

Math and Computation​

Using System.Math​


# Square root

$sqrt = [System.Math]::Sqrt(144)    # 12



# Rounding

$rounded = [System.Math]::Round(3.14159, 2)    # 3.14



# Power

$power = [System.Math]::Pow(2, 10)    # 1024



# Constants

$pi = [System.Math]::PI               # 3.14159265358979



# Trigonometric functions

$cos = [System.Math]::Cos(0)           # 1

Code explanation: System.Math is a static class containing optimized mathematical functions. These methods are compiled in the .NET runtime and are generally faster than PowerShell-native arithmetic for complex operations.

LINQ for Collection Operations​

LINQ (Language Integrated Query) provides high-performance collection operations.


# Load LINQ

Add-Type -AssemblyName System.Linq



# Create a large collection

$numbers = 1..1000000



# Sum (PowerShell)

$sum = 0

foreach ($n in $numbers) { $sum += $n }



# Sum (LINQ) - much faster

$sum = [System.Linq.Enumerable]::Sum($numbers)



# Filter with LINQ

$filtered = [System.Linq.Enumerable]::Where($numbers, [Func[int,bool]]{ $args[0] -gt 500000 })

Code explanation: LINQ operations are executed in compiled .NET code, often 100x faster than PowerShell loops for large collections.

Native PowerShell Math (PowerShell 7+)​

PowerShell 7+ includes native operators and methods that may be faster than System.Math for some operations. Always measure performance in your specific context.


Performance-Critical Loops​

Using .NET Collections​


# Slow: PowerShell array with +=

$list = @()

foreach ($i in 1..100000) {

    $list += $i

}



# Fast: .NET ArrayList

$list = [System.Collections.ArrayList]::new()

foreach ($i in 1..100000) {

    $null = $list.Add($i)

}



# Fastest: .NET List[T]

$list = [System.Collections.Generic.List[int]]::new()

foreach ($i in 1..100000) {

    $list.Add($i)

}

Code explanation: PowerShell arrays are fixed-size; += creates a new array each time. ArrayList and List[T] are dynamic and resize efficiently.

Suppressing Output​

Writing objects to the pipeline when they're not needed wastes resources. The fastest methods are assigning to $null and casting to [void].

MethodRelative Speed (10,240 iterations)Assign to $null1x (fastest)Redirect to $null1.52xCast to [void]1.71xPipe to Out-Null2.22x (slowest)


# Fastest

$null = $collection.Add($item)



# Fast

[void]$collection.Add($item)



# Avoid: slowest

$collection.Add($item) | Out-Null

When to Use .NET Directly​

Use .NET directly when:

Stick with cmdlets when:

Note: Many of the techniques described here aren't idiomatic PowerShell and may reduce readability. Script authors are advised to use idiomatic PowerShell unless performance dictates otherwise.


Summary​

Calling .NET classes directly is the most effective way to improve PowerShell performance. The key techniques are:

These practices produce scripts that are dramatically faster, making them suitable for enterprise-scale automation.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Pipeline Optimization

Next

Parallel Execution