Powershell String Length Validation

16,959

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!"
Share:
16,959
Reza Aghaei
Author by

Reza Aghaei

Updated on June 19, 2022

Comments

  • Reza Aghaei
    Reza Aghaei almost 2 years

    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?