PowerShell验证整形变量


适用于PowerShell4.0或者更高版本。

你可能知道在PowerShell定义变量时,可以使用[int]强类型,限定变量只能是整形。但是你是否知道,我们还可以使用正则表达式在整数类型上面再加一层验证,保证变量的值,只能是特定的整数类型。

比入我想限定一个整数,只能是2-6为的整数:

PS> [ValidatePattern('^\d{2,6}$')][int]$id = 666
PS> $id=12
PS> $id=123456
PS> $id=1
The variable cannot be validated because the value 1 is not a valid value for the id variable.
At line:1 char:1
+ $id=1
+ ~~~~~
 + CategoryInfo : MetadataError: (:) [], ValidationMetadataException
 + FullyQualifiedErrorId : ValidateSetFailure

PS> $id = 1234567
The variable cannot be validated because the value 1234567 is not a valid value for the id variable.
At line:1 char:1
+ $id = 1234567
+ ~~~~~~~~~~~~~
 + CategoryInfo : MetadataError: (:) [], ValidationMetadataException
 + FullyQualifiedErrorId : ValidateSetFailure

原文连接:Validating Integer Variables

本文链接: https://www.pstips.net/89efb.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

关于 Mooser Lee

我是一个Powershell的爱好者,创建了PowerShell中文博客,热衷于Powershell技术的搜集和分享。本站部分内容来源于互联网,不足之处敬请谅解,并欢迎您批评指正。

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注