如果在PowerShell类的方法中调用MessageBox,则MessageBox不会被显示。

3

我有一个PowerShell函数,如果我使用消息框向用户提供反馈,它可以正常工作。但是我想将该函数添加到一个类中。类方法可以正常工作,除了这行代码:

[system.windows.forms.messagebox]::show("The folder path does contain the right parameters.")

它一直给我报错:
Unable to find type: [System.Windows.Forms.Messagebox]

我在网上尝试了所有能找到的方法。我创建了一个非常简单的类,如下所示,它将在ISE中显示消息框,但如果我在PowerShell窗口中运行它,则不会显示消息框。我只是不知道如何找出原因。

class test {
    [void]ok() {
        Add-Type -AssemblyName "System.Windows.Form"
        [void][System.Windows.Forms.Messagebox]::Show("This works in ISE but not powershell window")
    }
}

$e = [test]::new()
$e.ok()

我相信这个问题有一个简单的答案,但我不知道是什么。


1
当您使用[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Form")时会发生什么? - undefined
1
这里应该是System.Windows.Forms,而不是System.Windows.Form。 - undefined
谢谢提醒,漏掉了S是我打字错误,我不得不重新输入脚本。它明确写着System.Windows.Forms。另外,[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")没有改进。我进行了更多的测试,发现脚本只在以管理员身份运行的Powershell(x86)中有效。无论是右键点击并使用Powershell运行,还是从其他任何Powershell命令窗口运行,都无法运行。我将编辑问题以寻求进一步澄清。 - undefined
@DanielGREEN - 请不要编辑问题以使答案过时。如果您有更新,请将其添加到现有问题的末尾。如果您想问一些新的问题,请提出一个新的问题。 - undefined
2个回答

1
我已经进行了一些测试,并确定此脚本仅在以管理员身份运行的Powershell(x86)命令窗口中调用脚本时才会运行。当我从任何其他版本的Powershell调用脚本,包括右键单击脚本并告诉它在Powershell中运行时,它会给我一个错误:

无法找到类型[System.Windows.Forms.Messagebox]

class test {

[void]ok() {

 Add-Type -AssemblyName "System.Windows.Forms"
 [void][System.Windows.Forms.Messagebox]::Show("This works in ISE but not powershell window")
}
}

$e = [test]::new()
$e.ok()

然而,当我按照以下方式将其转换为函数时,它可以正常工作。
function test {

 Add-Type -AssemblyName "System.Windows.Forms"
 [void][System.Windows.Forms.Messagebox]::Show("This works in ISE but not powershell window")
}

test

有人能否解释一下是什么原因导致了这种行为?


0

哦,是的,你说得对,答案很简单。你想要加载的程序集名为“System.Windows.Forms”

祝你周末愉快!


抱歉,那是个打字错误。我已经进行了更多的测试,并相应地编辑了我的问题。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接