PowerShell

PowerShell: When to use Add-Type and New-Object ?

In this blog post, I will discuss when you need to add classes with Add-Type and when you can provide classes with New-Object. I would say, let’s get started.

New-Object

Predefined .NET classes: PowerShell makes certain predefined .NET classes directly available without you having to load them with “Add-Type”.

You can simply use “New-Object, to create instances of these classes. This includes many commonly used classes such as “System.String”, “System.DateTime”, “System.IO.FileInfo”

Here are some examples:

$player = New-Object System.Media.SoundPlayer "$env:windir\Media\windows logon.wav" -Verbose
$player | Get-Member
$player.PlayLooping() # Methode tu etwas ==> Looping
$player.Stop() # Methode ==> Stop

[System.Math]::Round('123.6',0)

Add-Type

User-defined classes or external .NET assemblies: If you have created a user-defined NET class or want to access functions and classes in external .NET assemblies that are not available by default in PowerShell, you must use the “Add-Type” to load the class or assembly at runtime. After that you can use “New-Object” to create instances of these loaded classes.

Here are some examples:

[Microsoft.VisualBasic]::InputBox("Enter a computer name", "Computer") # Error. Wird nicht gefunden

Add-Type -AssemblyName Microsoft.VisualBasic # adds a .NET class to this session
$computer = [Microsoft.VisualBasic.Interaction]::InputBox("Enter a computer name", "Computer")
$Test = Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue
If ($Test.Status -eq 'Success') {
    [Microsoft.VisualBasic.Interaction]::MsgBox("Test for $computer successful.", "OKOnly,SystemModal,Information", "Success")
}
else {
[Microsoft.VisualBasic.Interaction]::MsgBox("Test for $computer failed.", "OKOnly,SystemModal,Critical", "Error")
}

By the way, you can list all predefined classes that are accessible without having to load them into the session.

Get-TypeData -TypeName '*'

I hope that was helpful and well explained. See you next time.

Categories: PowerShell

Tagged as: ,

2 replies »

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.