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

不想你离开。 提交于 2021-02-17 05:39:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!