$intVar = [int]$intVar
在这种情况下应该工作得很好。
$intVar.GetType() # String $intVar = [int]$intVar $intVar.GetType() # Int32
检查问题源文本中的错误消息可以看出这一点 的 你的字符串包含不可见的 LEFT-TO-RIGHT-MARK Unicode字符( U+200E ) 强> 这就是转换失败的原因。
U+200E
删除该字符将使转换成功,在最简单的情况下,通过简单地消除所有非数字字符来实现。从字符串:
# Simulate the input string with the invisible control char. $intStr = [char] 0x200e + '5' # FAILS, due to the invisible Unicode char. [int] $intStr # -> ... "Input string was not in a correct format." # OK - eliminate non-digits first. # Note the required (...) for proper precedence. [int] ($intStr -replace '\D') # -> 5
的 可选阅读:检查字符串的字符: 强>
# Print the code points of the string's characters: PS> [int[]] [char[]] $intStr 8206 # decimal equivalent of 0x200e, the LEFT-TO-RIGHT-MARK 53 # decimal equivalent of 0x54, the DIGIT FIVE # Show the code points in hex. format and print the char. PS> [char[]] $intStr | Select-Object @{ n='CodePoint'; e={ 'U+{0}' -f ([int] $_).ToString('X4') } }, @{ n='Char'; e={ $_ } } CodePoint Char --------- ---- U+200E ? U+0035 5
你也可以使用 Format-Hex ,但格式不容易在视觉上解析:
Format-Hex
PS> $intStr | Format-Hex -Encoding BigEndianUnicode 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 00000000000000000000 20 0E 00 35 ..5
-Encoding BigEndianUnicode 使用(UTF16-BE) - 即使使用.NET字符串 Unicode (UTF16-LE) - 这样就不约而同 字节 面向显示器首先显示16位代码单元的高字节,其读取更自然。
-Encoding BigEndianUnicode
Unicode
字节对 20 0E 是第一个代码单元, U+200E (从左到右的标记),和 00 35 第二个, U+0035 (数字 5 )。
20 0E
00 35
U+0035
5
右边的印刷字符的用处有限,因为它们是 字节 - 输入字节的单独解释,仅按预期呈现8位范围内的字符(代码点< = U+00FF );一个 0x0 byte表示为a .
U+00FF
0x0
.