In Powershell how can I convert a string with a trailing 'sign' to a number?
-
08-07-2019 - |
Question
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.
Solution
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);
OTHER TIPS
[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
Here's a better way to get the enum values:
$type = [System.Globalization.NumberStyles]
[enum]::GetValues($type)
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.