解释 PowerShell 高级函数中的强制属性。
powershellmicrosoft technologiessoftware & coding更新于 2026/1/7 8:37:17
下面有一个 PowerShell 高级函数的示例,我们将尝试理解强制参数的工作原理。
function math_Operation{
[cmdletbinding()]
param([int]$val1,[int]$val2)
Write-Host "乘法:$($val1*$val2)"
Write-Host "加法:$($val1+$val2)"
Write-Host "减法:$($val1-$val2)"
Write-Host "Divide : $($val1+$val2)"
}
执行上述示例时,如果未提供值,脚本将不会要求您输入值,默认情况下,它会获取值并执行程序。请参阅下面的执行示例。
PS C:\WINDOWS\system32> math_Operation 乘法 : 0 加法 : 0 减法 : 0 除法 : 0
即使您指定了两个变量 ($val1, $val2),如果您未提供它们,函数也不会要求您输入值,而是会获取空值。要使它们成为必需,请使用强制参数,如下所示。
函数 math_Operation{
[cmdletbinding()]
param([parameter(Mandatory=$True)]
[int]$val1,
[Parameter(Mandatory=$True)]
[int]$val2)
Write-Host "乘法 : $($val1*$val2)"
Write-Host "加法 : $($val1+$val2)"
Write-Host "减法 : $($val1-$val2)"
Write-Host "除法 : $($val1+$val2)"
}
输出 −
PS C:\WINDOWS\system32> math_Operation cmdlet math_Operation 位于命令管道位置 1 请提供以下参数的值: val1: 20 val2: 10 乘法:200 加法:30 减法:10 除法:30
正如您在输出中看到的,当您提到强制参数时,脚本会在您执行时询问这些变量的值,而无需提供值。如果您不提供变量的值,会发生什么情况?强制参数会接受该值吗?是的,它会接受。它接受 NULL 值作为整数变量的默认值。请参阅下面的输出。
PS C:\WINDOWS\system32> math_Operation cmdlet math_Operation at command pipeline position 1 Supply values for the following parameters: val1: val2: Multiply : 0 Addition : 0 Subtraction : 0 Divide : 0
请记住,上述默认值 0 对于数据类型为 Integer 的单变量是可接受的,但如果使用整数数组 (int[]),则 PowerShell 将不接受空数组,例如
function print_number{
[cmdletbinding()]
param(
[parameter(Mandatory=$True)]
[int[]]$numbers
)
Write-Output "Integer Array"
$numbers
}
输出 −
PS C:\WINDOWS\system32> print_number cmdlet print_number at command pipeline position 1 Supply values for the following parameters: numbers[0]: print_number : Cannot bind argument to parameter 'numbers' because it is an empty array. At line:1 char:1 + print_number + ~~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [print_number], ParameterBindin g ValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyArrayNotAll o wed,print_number
但是,如果为字符串值和字符串数组提供空输入,它们都不接受空字符串或空字符串。
示例
function print_String{
[cmdletbinding()]
param(
[parameter(Mandatory=$True)]
[string]$name,
[parameter(Mandatory=$True)]
[string[]]$names
)
$name
$names
}
输出
PS C:\WINDOWS\system32> print_String cmdlet print_String at command pipeline position 1 Supply values for the following parameters: name: print_String : Cannot bind argument to parameter 'name' because it is an empty string. At line:1 char:1 + print_String + ~~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [print_String], ParameterBindin g ValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAl l owed,print_String
从上述示例可以得出的结论是,当指定强制参数时,是否接受 null 或空值取决于数据类型,并且没有任何集合接受 null 值。

