0

I've created a Powershell function that takes in a string. I'm trying to validate that the char count of a string param is over 4, however whenever I check the param, the count is always 1.

Why is this so?

function DeleteSitesWithPrefix($prefix){

    if([string]::IsNullOrEmpty($prefix)){
        Write-Host "Please provide the name of the csv file to use"
        return
    }

    if([string]::$prefix.Length -lt 4){
        Write-Host "Please provide a prefix of 4 or more digits"
        return
    }
1
  • 1
    Why don't you just use if ($prefix.Length -lt 4) {...? Commented Mar 24, 2016 at 10:43

2 Answers 2

3

Consider rewriting your function using validation attributes:

function DeleteSitesWithPrefix
{
    Param(
        [Parameter(Mandatory = $true)]
        [ValidateScript({$_.Length -ge 4})]
        [ValidateNotNullOrEmpty()]
        [string]$Prefix
    )

    # Do stuff...
}
Sign up to request clarification or add additional context in comments.

1 Comment

ValidateNotNullOrEmpty() is redundant, since null/empty values have a (string) length of 0.
0

[string]:: means calling a static method of string, but $prefix.Length is not such a method.

this will work:

if($prefix.Length -lt 4){
    Write-Host "Please provide a prefix of 4 or more digits"
    return
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.