Add Type - PowerShell
Overview
The Add-Type
command allows you to dynamically add types, methods, and properties to the PowerShell runtime. It is primarily used to load or define new types in memory, enabling the creation of custom objects, extending existing types, and integrating with .NET assemblies and external libraries.
Syntax
Add-Type [-AssemblyName] <string> [-TypeDefinition] <string> [-Language] <string>
Add-Type [-AssemblyFile] <string> [-TypeDefinition] <string> [-Language] <string>
Add-Type [-MemberDefinition] <string> [-Language] <string>
Options/Flags
- -AssemblyName: The name of the .NET assembly containing the type definition.
- -AssemblyFile: The path to the .NET assembly file containing the type definition.
- -TypeDefinition: The fully qualified name of the type to add.
- -Language: The language used to define the type. Default is “C#”.
- -MemberDefinition: A string containing the definition of the type member to add.
Examples
Load a Type from an Assembly:
Add-Type -AssemblyName System.Data
Add a Custom Type:
Add-Type -MemberDefinition @"
public class Person {
public string Name { get; set; }
}
"@
Extend an Existing Type:
Add-Type -MemberDefinition @"
public void ExtendMethod(string parameter) { }
"@ -TypeDefinition System.String
Common Issues
- Assembly Not Found: Ensure that the specified assembly exists and is accessible to the PowerShell session.
- Type Not Found: Verify that the type definition provided is correct and exists within the specified assembly.
- Syntax Errors: Double-check the syntax of the type definition or member definition strings.
Integration
Add-Type
can be used in combination with other PowerShell commands to create dynamic objects or pipelines:
$Type = Add-Type -MemberDefinition "..."
$Objects = @()
$Type.InvokeMember("New", 'CreateInstance', $null, @()) | Foreach-Object {
$Objects += $_
}
Related Commands
Get-Assembly
Get-Member
New-Object