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:
Name
parameters longer than 10 characters.10
without any extension.What's the problem with my script and How can I validate string length in PowerShell?
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!"