Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

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

How do test if the number of characters in $dbUserName is more than eight characters?

I have been unable to locate a command or series of commands that will let me do this. I have only been able to find if the variable is null:

if ($dbUserName) {
    Write-Output " You left Username blank"
    $dbUserName = read-host
}

But I would like to next test like this:

if ($dbUserName [String] > 8 ) }
    Write-Output " Please enter more than 8 characters "
    $dbUserName=read-host " Re-enter database user name"
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 (>=)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...