首页 > 解决方案 > 从 Powershell 5 移植到 Powershell 7 的函数失败,并显示“对象引用未设置为对象的实例”

问题描述

以下代码在 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)
}

但是,在 powershell 7.1.0(预览版 5)中,执行失败并显示“对象引用未设置为对象的实例”,我实际上迷路了。谷歌搜索并没有多大帮助,因为看起来这个错误可能会在非常不同的上下文中遇到。所以,PowerShell 专家,问你一个问题,我该如何解决这个问题。

在此处输入图像描述

我试图在 body ( object reference not set to an instance of an object) 中声明参数,希望可能存在一些语义差异,但这并没有帮助。

标签: powershellpowershell-7.0

解决方案


这是一个已知问题,因为某些所需的功能在构建 PS v7 的 .NET Core 中不存在。看起来像提出了一个错误,但它在没有修复的情况下被关闭:

System.Speech.Synthesis.SpeechSynthesizer Speak 方法抛出未设置为对象实例的对象引用。”在 PowerShell 6.1.2 中


推荐阅读