Sunday, September 8, 2024
HomePowershellWhen to make use of Add-Kind and New-Object ? – SID-500.COM

When to make use of Add-Kind and New-Object ? – SID-500.COM


On this weblog publish, I’ll talk about when it is advisable to add courses with Add-Kind and when you’ll be able to present courses with New-Object. I’d say, let’s get began.

New-Object

Predefined .NET courses: PowerShell makes sure predefined .NET courses immediately obtainable with out you having to load them with “Add-Kind”.

You’ll be able to merely use “New-Object, to create situations of those courses. This contains many generally used courses resembling “System.String”, “System.DateTime”, “System.IO.FileInfo”

Listed below are some examples:

$participant = New-Object System.Media.SoundPlayer "$env:windirMediawindows logon.wav" -Verbose
$participant | Get-Member
$participant.PlayLooping() # Methode tu etwas ==> Looping
$participant.Cease() # Methode ==> Cease

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

Add-Kind

Consumer-defined courses or exterior .NET assemblies: In case you have created a user-defined NET class or wish to entry features and courses in exterior .NET assemblies which can be not obtainable by default in PowerShell, you could use the “Add-Kind” to load the category or meeting at runtime. After that you should utilize “New-Object” to create situations of those loaded courses.

Listed below are some examples:

[Microsoft.VisualBasic]::InputBox("Enter a pc identify", "Pc") # Error. Wird nicht gefunden

Add-Kind -AssemblyName Microsoft.VisualBasic # provides a .NET class to this session
$laptop = [Microsoft.VisualBasic.Interaction]::InputBox("Enter a pc identify", "Pc")
$Check = Check-Connection -ComputerName $laptop -Rely 1 -ErrorAction SilentlyContinue
If ($Check.Standing -eq 'Success') {
    [Microsoft.VisualBasic.Interaction]::MsgBox("Check for $laptop profitable.", "OKOnly,SystemModal,Info", "Success")
}
else {
[Microsoft.VisualBasic.Interaction]::MsgBox("Check for $laptop failed.", "OKOnly,SystemModal,Vital", "Error")
}

By the best way, you’ll be able to listing all predefined courses which can be accessible with out having to load them into the session.

Get-TypeData -TypeName '*'

I hope that was useful and effectively defined. See you subsequent time.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments