views:

2047

answers:

4

I need to convert strings with optional trailing signs into actual numbers using Powershell.

Possible strings are:

  • 1000-
  • 323+
  • 456

I'm trying to use System.Int.TryParse with a NumberStyles of AllowTrailingSign, but I can't work out how to make System.Globalization.NumberStyles available to Powershell.

A: 

If you are sure that the signs could be - or +, String.Replace could help.

If you mean that 323- should return -323, checking for the sign and multiplying it by -1 would help.

shahkalpesh
+2  A: 
[System.Globalization.NumberStyles]::AllowTrailingSign

I should also point out, that when I'm dealing with enums in general, sometimes I can get by typing a string. E.g. in this case, just put

"AllowTrailingSign"

Final note, when quizzing an Enum for all possible values, use the line:

[System.Globalization.NumberStyles] | gm -static
Peter Seale
+5  A: 

EDIT: as per Halr9000's suggestion

$foo = "300-";
$bar = 0;
$numberStyles = [System.Globalization.NumberStyles];
$cultureInfo = [System.Globalization.CultureInfo];

[int]::TryParse($foo, $numberStyles::AllowTrailingSign, $cultureInfo::CurrentCulture, [ref]$bar);
Jim Burger
+1  A: 

Here's a better way to get the enum values:

$type = [System.Globalization.NumberStyles]
[enum]::GetValues($type)
halr9000
Seems to me you mean: $type = [System.Globalization.NumberStyles];[enum]::GetValues($type);
Jim Burger