解释 PowerShell 高级函数中的 AllowEmptyString() 和 AllowEmptyCollection()。
powershellmicrosoft technologiessoftware & coding更新于 2026/1/7 8:22:17
AllowEmptyString() 属性适用于字符串变量,而 AllowEmptyCollection() 属性适用于不同数据类型的数组(集合)。
请考虑以下示例。这里,我们使用了一个强制变量 $name(它是一个字符串)和 $stringarray(它是一个字符串数组)。
function print_String{
[cmdletbinding()]
param(
[parameter(Mandatory=$True)]
[string]$name,
)
Write-Output "Writing a single string"
$name
}
如果我们获取上述变量的输出,则会生成以下错误。
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
如上输出所示,脚本不接受空字符串。要允许空字符串,您需要使用 AllowEmptyString() 参数,这样就不会产生错误。
function print_String{
[cmdletbinding()]
param(
[parameter(Mandatory=$True)]
[AllowEmptyString()]
[string]$name
)
Write-Output "Writing a single string"
$name
}
输出−
PS C:\WINDOWS\system32> print_String cmdlet print_String at command pipeline position 1 Supply values for the following parameters: name: Writing a single string
在上面的例子中,您可以看到,一旦您添加参数 AllowEmptyString(),程序就会接受空字符串。同样,当您添加 AllowEmptyCollection() 参数时,PowerShell 将接受数组的空值。
function print_String{
[cmdletbinding()]
param(
[parameter(Mandatory=$True)]
[AllowEmptyCollection()]
[string[]]$stringarray
)
Write-Output "Writing a string array"
$stringarray
}
输出
PS C:\WINDOWS\system32> print_String cmdlet print_String at command pipeline position 1 Supply values for the following parameters: stringarray[0]: Writing a string array

