Search code examples
validationpowershellmatchlimit

Powershell validate input


I'm trying to validate some input in powershell. The user should enter a username for a new AD user. This username should be validated for any invalid characters (e.g !, $, ;, etc). Valid characters are a-z (upper and lower), 0-9, _, - and ,

Thanks for any help.

At the moment my code looks like this:

do{

    $input="notok"
    # Eingabe es Usernamen
    Write-Host "Bite den Usernamen eingeben"
    $Username = Read-Host


    if ($Username -notmatch "[a-zA-Z0-9_.-]") {
        Write-Host ""
        Write-Host "ACHTUNG: Benutzer $Username enthaelt ungueltige Zeichen (nur a-z, A-Z, 0-9, ., - und _ erlaubt), bitte die Eingabe wiederholen" -ForegroundColor Red
        Write-Host ""
        $input="notok"

    }else{

        $input="ok"

    }

}while($input -ne "ok")

Solution

  • Try this:

    do{
    
        $input="notok"
        # Eingabe es Usernamen
        Write-Host "Bite den Usernamen eingeben"
        $Username = Read-Host
    
    
        if ($Username -notmatch "^[a-z0-9_.-]*$") {
            Write-Host ""
            Write-Host "ACHTUNG: Benutzer $Username enthaelt ungueltige Zeichen (nur a-z, A-Z, 0-9, ., - und _ erlaubt), bitte die Eingabe wiederholen" -ForegroundColor Red
            Write-Host ""
            $input="notok"
    
        }else{
    
            $input="ok"
    
        }
    
    }while($input -ne "ok")