问题
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 Nameparameters longer than 10 characters.
- Every time I execute it, it creates and updates a file named 10without 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