Poweshell-在类方法中使用MessageBox

时间:2018-11-23 11:22:45

标签: powershell class methods messagebox

我有一个Powershell函数,该函数在使用消息框向用户提供一些反馈的地方工作得很好。我想将函数添加到Class中。除非我将以下行留在以下位置,否则Class方法工作正常:

[system.windows.forms.messagebox] :: show(“文件夹路径确实包含正确的参数。”)

它总是提示我无法找到类型:

[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()

我确定对此有一个简单的答案,但是我不知道它是什么。

2 个答案:

答案 0 :(得分:0)

哦,是的,您是对的,答案非常简单。您要加载的程序集称为“ System.Windows.Form s

周末愉快!

答案 1 :(得分:0)

我已经进行了一些测试,并且确定仅当我从以管理员身份运行的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

任何人都可以阐明造成这种现象的原因吗?