Powershell 调用带有字符串变量的函数
Powershell call Function with String Variable
function add($n1, $n2){
return $n1 + $n2
}
$num1 = 1
$num2 = 2
$operand = "add"
########################################################################
# Given the above scenario, please try to make the next line work:
# $operand $num1 $num2 -> My ATTEMPT to call function via string variable
add $num1 $num2 # This is what I am trying to achieve with the above line
请演示如何使用字符串变量“Operand”调用函数。
只要函数已加载到内存中,当函数名称存储在变量 ($operand
) 中时,调用函数的两种最常见方式是使用call operator &
:
& $operand $num1 $num2 # => 3
. $operand $num1 $num2 # => 3
您也可以使用 Invoke-Expression
(even though not recommended),只要表达式被包装为 string:
Invoke-Expression "$operand $num1 $num2" # => 3
补充, here is a different way that uses a hashtable
of script blocks:
$funTable = @{
add = { param($n1, $n2) $n1 + $n2 }
sub = { param($n1, $n2) $n1 - $n2 }
}
或者你可以引用函数(之前必须已经定义):
$funTable = @{
add = $function:add
sub = $function:sub
}
现在您可以像这样通过字符串变量调用函数:
$operand = 'add'
& $funTable.$operand $num1 $num2
# Just a different syntax, it's a matter of taste
$funTable.$operand.Invoke( $num1, $num2 )
您可以使用 .
代替 &
,但在大多数情况下不推荐这样做。不同之处在于,使用 .
,函数定义的任何临时变量都会泄漏到调用者的范围内,但您通常希望自动删除这些变量,这就是 &
所做的。
使用 hashtable
的优势:
- 操作数函数按逻辑分组。
- 当函数名称是用户输入时,他们不能 运行 任意 PowerShell 代码(使用
& $operand
就可以)。他们只能 运行 您存储在 $funTable
中的函数。否则他们会得到一个错误。
function add($n1, $n2){
return $n1 + $n2
}
$num1 = 1
$num2 = 2
$operand = "add"
########################################################################
# Given the above scenario, please try to make the next line work:
# $operand $num1 $num2 -> My ATTEMPT to call function via string variable
add $num1 $num2 # This is what I am trying to achieve with the above line
请演示如何使用字符串变量“Operand”调用函数。
只要函数已加载到内存中,当函数名称存储在变量 ($operand
) 中时,调用函数的两种最常见方式是使用call operator &
:
& $operand $num1 $num2 # => 3
. $operand $num1 $num2 # => 3
您也可以使用 Invoke-Expression
(even though not recommended),只要表达式被包装为 string:
Invoke-Expression "$operand $num1 $num2" # => 3
补充hashtable
of script blocks:
$funTable = @{
add = { param($n1, $n2) $n1 + $n2 }
sub = { param($n1, $n2) $n1 - $n2 }
}
或者你可以引用函数(之前必须已经定义):
$funTable = @{
add = $function:add
sub = $function:sub
}
现在您可以像这样通过字符串变量调用函数:
$operand = 'add'
& $funTable.$operand $num1 $num2
# Just a different syntax, it's a matter of taste
$funTable.$operand.Invoke( $num1, $num2 )
您可以使用 .
代替 &
,但在大多数情况下不推荐这样做。不同之处在于,使用 .
,函数定义的任何临时变量都会泄漏到调用者的范围内,但您通常希望自动删除这些变量,这就是 &
所做的。
使用 hashtable
的优势:
- 操作数函数按逻辑分组。
- 当函数名称是用户输入时,他们不能 运行 任意 PowerShell 代码(使用
& $operand
就可以)。他们只能 运行 您存储在$funTable
中的函数。否则他们会得到一个错误。