Here's the problem. To simplify a complex script, I have built a small menu.
- Quit
- User1
- User2
- ...
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.
10
PS PS:\> $answer
8
PS PS:\> $answer -lt $counter
False
Why?? Why oh Why? Here's what I found..
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:
outside my function, it now functions correctly. Whew!
Comments
PowerShell Function output feature
#You can cut and paste this post into PowerShell
#Problem
Function IsNumeric ([string] $a) {
[reflection.assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
$b = [Microsoft.VisualBasic.Information]::isnumeric($a)
Return $b
}
IsNumeric(1)
#GAC Version Location
#--- ------- --------
#True v2.0.50727 C:\WINDOWS\assembly\GAC_MSIL\Microsoft.VisualBasic...
#True
#Check to see why we're getting two responses
IsNumeric(1) | foreach {$_.GetType().Fullname}
#System.Reflection.Assembly
#System.Boolean
#PowerShell feature; functions return everything not captured
#Either capture or [void] System.Reflection.Assembly to return just the Boolean
#Solution
Function IsNumeric ([string] $a) {
[void][reflection.assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
$b = [Microsoft.VisualBasic.Information]::isnumeric($a)
Return $b
}
IsNumeric(1) | foreach {$_.GetType().Fullname}
#System.Boolean
Thanks Bucky!!
Sorry about the spam filter, I am still training it..
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