Understanding the Power of Add-Type in PowerShell
Welcome back to Wahmans PowerShell Blog! Today, we’re diving into a very powerful yet often underutilized cmdlet in the PowerShell ecosystem – Add-Type. According to Microsoft’s documentation, Add-Type “adds a Microsoft .NET class to a PowerShell session,” but what does that mean in practice, and how can you use it to enhance your scripting superpowers? Let’s explore!
What is Add-Type?
Add-Type allows you to define and use .NET types directly in your PowerShell session. This can include custom C# classes, structs, enums, and even importing existing .NET assemblies. With this capability, you’re not just limited to PowerShell’s native commands—you can tap into the full power of the .NET framework, right from your script!
Example 1: Beginner – Creating a Simple C# Class
Let’s start with a simple example. Say you want to create a class to represent a Person with a Name property.
Add-Type -TypeDefinition @"
public class Person
{
public string Name { get; set; }
}
"@
$john = New-Object Person
$john.Name = "John Doe"
$john.Name
Output:
John Doe
Example 2: Intermediate – Using Add-Type to Access Win32 APIs
You can also use Add-Type to tap into native Windows APIs. Let’s say you want to use the default beep sound from the console.
Add-Type -MemberDefinition @"
[DllImport("kernel32.dll")]
public static extern bool Beep(int freq, int duration);
"@ -Name "Win32Audio" -Namespace "Utilities" -UsingNamespace System.Runtime.InteropServices -PassThru
[Utilities.Win32Audio]::Beep(750, 300)
This will play a short beep at 750Hz for 300 milliseconds.
Example 3: Advanced – Using Static Methods and Custom Logic
Here’s how you might add a C# class with some static utility logic:
Add-Type -TypeDefinition @"
public static class MathUtils
{
public static int Square(int x)
{
return x * x;
}
}
"@
[MathUtils]::Square(5)
Output:
25
Example 4: Advanced – Embedding Full C# Classes with Constructors
Let’s embed a fully-featured C# class including properties, a constructor and method.
Add-Type -TypeDefinition @"
public class TimerWrapper
{
private System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
public void Start() { sw.Start(); }
public void Stop() { sw.Stop(); }
public double ElapsedSeconds { get { return sw.Elapsed.TotalSeconds; } }
}
"@
$timer = New-Object TimerWrapper
$timer.Start()
Start-Sleep -Seconds 2
$timer.Stop()
$timer.ElapsedSeconds
This will output approximately 2.0 seconds.
Wrapping Up
As you can see, Add-Type opens up a whole new world of possibilities in your PowerShell scripting endeavors. Whether you’re creating simple C# objects or diving deep into platform API calls and custom utilities, the sky’s the limit.
Happy scripting, and I will see you in the next post!
Leave a Reply