I need to convert strings with optional trailing signs into actual numbers using Powershell.
我需要使用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.
我正在尝试使用带有NumberStyles的AllowTrailingSign的System.Int.TryParse,但我无法弄清楚如何使Powershell可以使用System.Globalization.NumberStyles。
4 个解决方案
#1
5
EDIT: as per Halr9000's suggestion
编辑:根据Halr9000的建议
$foo = "300-";
$bar = 0;
$numberStyles = [System.Globalization.NumberStyles];
$cultureInfo = [System.Globalization.CultureInfo];
[int]::TryParse($foo, $numberStyles::AllowTrailingSign, $cultureInfo::CurrentCulture, [ref]$bar);
#2
2
[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
#3
1
Here's a better way to get the enum values:
这是获取枚举值的更好方法:
$type = [System.Globalization.NumberStyles]
[enum]::GetValues($type)
#4
0
If you are sure that the signs could be - or +, String.Replace could help.
如果您确定标志可以是 - 或+,String.Replace可能会有所帮助。
If you mean that 323- should return -323, checking for the sign and multiplying it by -1 would help.
如果你的意思是323-应该返回-323,检查符号并将其乘以-1会有所帮助。
#1
5
EDIT: as per Halr9000's suggestion
编辑:根据Halr9000的建议
$foo = "300-";
$bar = 0;
$numberStyles = [System.Globalization.NumberStyles];
$cultureInfo = [System.Globalization.CultureInfo];
[int]::TryParse($foo, $numberStyles::AllowTrailingSign, $cultureInfo::CurrentCulture, [ref]$bar);
#2
2
[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
#3
1
Here's a better way to get the enum values:
这是获取枚举值的更好方法:
$type = [System.Globalization.NumberStyles]
[enum]::GetValues($type)
#4
0
If you are sure that the signs could be - or +, String.Replace could help.
如果您确定标志可以是 - 或+,String.Replace可能会有所帮助。
If you mean that 323- should return -323, checking for the sign and multiplying it by -1 would help.
如果你的意思是323-应该返回-323,检查符号并将其乘以-1会有所帮助。