shabunc
shabunc

Reputation: 24771

Function ported from Powershell 5 to Powershell 7 fails with "object reference not set to an instance of an object"

Following code works as expected in powershell 5.1:

function Get-Say([String] $Message, [String] $Voice = "Microsoft Irina Desktop") {
    Add-Type -AssemblyName System.speech
    $speak = New-Object System.Speech.Synthesis.SpeechSynthesizer
    $speak.SelectVoice($Voice)
    $speak.Speak($Message)
}

However in powershell 7.1.0 (preview 5) execution is failing with "object reference not set to an instance of an object" and I'm actually lost. Googling does not help much since it looks like this error can be encountered in very different context. So, PowerShell experts, a question to you, how can I fix this.

enter image description here

I've tried to declare params inside body (object reference not set to an instance of an object) in a faint hope that might be there's some semantic difference but that hadn't helped.

Upvotes: 2

Views: 364

Answers (1)

boxdog
boxdog

Reputation: 8442

This is a known issue and is due to the fact that some of the functionality required is not present in .NET Core, which PS v7 is built on. Looks like a bug was raised but it was closed without a fix:

System.Speech.Synthesis.SpeechSynthesizer Speak method throws Object reference not set to an instance of an object." in PowerShell 6.1.2

Upvotes: 4

Related Questions