Powershell String Length Validation

孤人 提交于 2020-03-03 09:18:46

问题


I created a really simple HelloWorld.ps1 Power-shell script which accepts a Name parameter, validates its length and then prints a hello message, for example if you pass John as Name, it's supposed to print Hello John!.

Here is the Power-shell script:

param (
    [parameter(Mandatory=$true)]
    [string]
    $Name
)
# Length Validation
if ($Name.Length > 10) {
    Write-Host "Parameter should have at most 10 characters."
    Break
}
Write-Host "Hello $Name!"

And here is the command to execute it:

.\HelloWorld.ps1 -Name "John"

The strange behavior is every time that I execute it:

  • It doesn't perform validation, so it accepts Name parameters longer than 10 characters.
  • Every time I execute it, it creates and updates a file named 10 without any extension.

What's the problem with my script and How can I validate string length in PowerShell?


回答1:


The problem - Using wrong operator

Using wrong operators is a common mistake in PowerShell. In fact > is output redirection operator and it sends output of the left operand to the specified file in the right operand.

For example $Name.Length > 10 will output length of Name in a file named 10.

How can I validate string length?

You can use -gt which is greater than operator this way:

if($Name.Length -gt 10)

Using ValidateLength attribute for String Length Validation

You can use [ValidateLength(int minLength, int maxlength)] attribute this way:

param (
    [ValidateLength(1,10)]
    [parameter(Mandatory=$true)]
    [string]
    $Name
)
Write-Host "Hello $Name!"


来源:https://stackoverflow.com/questions/46421158/powershell-string-length-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!