How can I test that a variable is more than eight characters in PowerShell? How can I test that a variable is more than eight characters in PowerShell? powershell powershell

How can I test that a variable is more than eight characters in PowerShell?


Use the length property of the [String] type:

if ($dbUserName.length -gt 8) {    Write-Output "Please enter more than 8 characters."    $dbUserName = Read-Host "Re-enter database username"}

Please note that you have to use -gt instead of > in your if condition. PowerShell uses the following comparison operators to compare values and test conditions:

  • -eq = equals (==)
  • -ne = not equals (!=)
  • -lt = less than (<)
  • -gt = greater than (>)
  • -le = less than or equals (<=)
  • -ge = greater than or equals (>=)


You can also use -match against a Regular expression. Ex:

if ($dbUserName -match ".{8}" ){    Write-Output " Please enter more than 8 characters "    $dbUserName=read-host " Re-enter database user name"}

Also if you're like me and like your curly braces to be in the same horizontal position for your code blocks, you can put that on a new line, since it's expecting a code block it will look on next line. In some commands where the first curly brace has to be in-line with your command, you can use a grave accent marker (`) to tell powershell to treat the next line as a continuation.