Oddity in Powershell operators

Here's the problem. To simplify a complex script, I have built a small menu.

  1. Quit
  2. User1
  3. User2
  4. ...

The list of users is dynamic (up to a maximum) defined as $counter. This dynamic list is composed of names from previous runs of the script (via being dotsourced). In addition to these users, I let the client type in names not defined in the subset, sort of a "Other" field.

PS PS:\> $counter
10
PS PS:\> $answer
8
PS PS:\> $answer -lt $counter
False

Why?? Why oh Why? Here's what I found..

PS PS:\> $counter -is [int32]
True
PS PS:\> $answer -is [int32]
False

"8" does not equal 8. In fact, "8" is greater than 10. I've tried to use the scriptcenter's isNumeric function, but had mixed results with it. The problem happens that I put the entire segment into a function.

 
Function IsNumeric ([string] $a) {
    [reflection.assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
    $b = [Microsoft.VisualBasic.Information]::isnumeric($a)
    Return $b
}

Problem is that my function was returning an array, containing both the vbScript load statement and $true or $false. I found that by moving:

  [reflection.assembly]::LoadWithPartialName("'Microsoft.VisualBasic")

outside my function, it now functions correctly. Whew!

Comments

That isn't an oddity, just

That isn't an oddity, just need to be careful with types. Since you probably used Read-Host, it returns a string. So cast the result as an integer:

[int]$answer = Read-Host ...

Something that needs to be watched for in dynamically typed languages.

Yes, but, I wanted both!

Ideally I wanted my script to accept both number values from a menu I displayed or a string of characters (user's mailbox info).

If I dot-source the code, the variable complains the second run. Hmm, give me an idea on why that error keeps coming up.

Thanks,

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <blockquote> <center> <hr> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <drupal6>, <html>, <java>, <javascript>, <php>, <posh>.

More information about formatting options