解释 PowerShell 高级函数中的 AllowEmptyString() 和 AllowEmptyCollection()。
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP