Richard Banks
Richard Banks

Reputation: 2983

Checking input to a Powershell function

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
    }

Upvotes: 0

Views: 80

Answers (2)

beatcracker
beatcracker

Reputation: 6920

Consider rewriting your function using validation attributes:

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

    # Do stuff...
}

Upvotes: 3

Falco Alexander
Falco Alexander

Reputation: 3332

[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
}

Upvotes: 0

Related Questions