Speeding Up New-Object Synthesizer

by Feb 1, 2017

New-Object creates new instances of objects, and you have seen one example in the past “Speech Week”: PowerShell was able to create a new speech synthesizer object, and convert text to speech:

Add-Type -AssemblyName System.Speech
$speak = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
$speak.Speak('Hello I am PowerShell!')

The approach is always the same, so when you use a different class like System.Net.NetworkInformation.Ping, you can ping IP addresses or host names:

$ping = New-Object -TypeName System.Net.NetworkInformation.Ping
$timeout = 1000
$result = $ping.Send('powershellmagazine.com', $timeout)

$result

In PowerShell 5 or better, there is an alternative to New-Object that works faster: the static method New() which is exposed by any type. You could rewrite the above examples like this:

Add-Type -AssemblyName System.Speech
$speak = [System.Speech.Synthesis.SpeechSynthesizer]::New()
$speak.Speak('Hello I am PowerShell!')

Likewise:

$ping = [System.Net.NetworkInformation.Ping]::New()
$timeout = 1000
$result = $ping.Send('powershellmagazine.com', $timeout)

$result

Or, if you prefer, even shorter:

[System.Net.NetworkInformation.Ping]::New().Send('powershellmagazine.com', 1000)

Note: once you use New() instead of New-Object, your code requires at least PowerShell 5.

Twitter This Tip! ReTweet this Tip!