PowerShell 中的函数重载 [英] Function overloading in PowerShell
问题描述
你能在 PowerShell 中重载函数吗?
Can you overload functions in PowerShell?
我想让我的函数接受一个字符串、数组或一些开关.
I want to my function to accept a string, array or some switch.
我想要的一个例子:
- Backup-UsersData singleUser
- Backup-UsersData @('Alice', 'Bob','乔')
- 备份-UsersData -all
推荐答案
在 PowerShell 中函数不会重载.最后一个定义覆盖同一范围内的前一个定义或隐藏父范围内的前一个定义.因此,您应该创建一个函数并提供一种通过参数区分其调用模式的方法.
In PowerShell functions are not overloaded. The last definition overrides the previous in the same scope or hides the previous in a parent scope. Thus, you should create a single function and provide a way to distinguish its call mode by arguments.
在 V2 中,您可以使用高级函数,请参阅 help about_Functions_Advanced_Parameters
并避免在解决参数集歧义时进行一些手动编码:
In V2 you may use an advanced function, see help about_Functions_Advanced_Parameters
and avoid some manual coding on resolving parameter set ambiguities:
# advanced function with 3 parameter sets
function Backup-UsersData
(
[Parameter(Position=0, ParameterSetName="user")]
[string]$user,
[Parameter(Position=0, ParameterSetName="array")]
[object[]]$array,
[Parameter(Position=0, ParameterSetName="all")]
[switch]$all
)
{
# use this to get the parameter set name
$PSCmdlet.ParameterSetName
}
# test
Backup-UsersData -user 'John'
Backup-UsersData 1, 2
Backup-UsersData -all
# OUTPUT:
# user
# array
# all
请注意,这种机制有时很奇怪.例如,在第一个测试中,我们必须明确指定参数名称 -user
.否则:
Note that this mechanism is sometimes strange. For example in the first test we have to specify parameter name -user
explicitly. Otherwise:
Backup-UsersData : Parameter set cannot be resolved using the specified named parameters.
At C:TEMP\_101015_110059 ry2.ps1:21 char:17
+ Backup-UsersData <<<< 'John'
+ CategoryInfo : InvalidArgument: (:) [Backup-UsersData], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Backup-UsersData
在许多情况下,标准的,而不是高级的,混合参数的函数可以:
In many cases standard, not advanced, function with mixed parameters will do:
function Backup-UsersData
(
[string]$user,
[object[]]$array,
[switch]$all
)
{
if ($user) {'user'}
elseif ($array) {'array'}
elseif ($all) {'all'}
else {'may be'}
}
Backup-UsersData -user 'John'
Backup-UsersData -array 1, 2
Backup-UsersData -all
Backup-UsersData
但在这种情况下,您应该解决(或接受并忽略)歧义,例如决定要做什么,如果,说:
But in this case you should resolve (or accept and ignore) ambiguities, e.g. to decide what to do if, say:
Backup-UsersData -user 'John' -array 1, 2 -all
这篇关于PowerShell 中的函数重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!