问题
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.
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.
回答1:
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
来源:https://stackoverflow.com/questions/62835479/function-ported-from-powershell-5-to-powershell-7-fails-with-object-reference-n