通过字符串作为块获取Powershell函数引用

时间:2019-05-16 19:10:30

标签: powershell

我正在尝试通过Add_Click将处理程序添加到表单/ wpf按钮。 我事先不知道函数名称,因此构造函数名称很重要。然后将其传递给Add_Click。

尝试以下操作,我会得到

$num = 1
function somefn1 () {}

$fn = $Function:"somefn$num"

$somebutton.Add_Click($fn)

错误是

Cannot convert argument "value", with value: "somefn1", for "add_Click" to type "System.Windows.RoutedEventHandler": "Cannot convert the 
"somefn1" value of type "System.String" to type "System.Windows.RoutedEventHandler"."
At xyz
+ ... $somebutton.Add_Click("somefn$num") }
+                              ~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

我不确定如何解决。有任何想法或提示吗?

1 个答案:

答案 0 :(得分:0)

工作:使用字符串附加现有功能(注意处理程序的范围)

$elName = "theButton"  # => Name="theButton"
$fnName = "mynamespace." + "function_name"

$fns = Get-ChildItem function: | Where-Object { $_.Name -like $fnName }
$Form.FindName($elName).Add_Click( $fns[0].ScriptBlock )

function mynamespace.function_name($Sender, $EventArgs) {
  Write-Host "works !"
}