显示 GetInvalidFileNameChars() 的 Powershell 输出的十六进制值

Show hex values of Powershell output of GetInvalidFileNameChars()

在 Windows 7 和 PowerShell v.2 中,我试图使用 [System.IO.Path]::GetInvalidFileNameChars().

查看它的无效字符列表

在提示符下输入时,它会列出字符,每行一个。我想要的是获取他们的十六进制(或十进制)代码。

阿蒙我试过的东西:

Expressions are only allowed as the first element of a pipeline.

The term 'Format-Hex' is not recognized ...

Cannot find an overload for "ToString" and the argument count: "1".

我熟悉 Bash、Perl,甚至是蹩脚的 cmd.exe,但不幸的是,我对 PowerShell 一无所知。

但我确信必须有一种简单易行的方法来列出这些字符的十六进制值。

更新: 多亏了下面的答案,我最终使用的命令是这个命令,除了十六进制值外,它还打印十进制值和字符本身:

ForEach ($c in [System.IO.Path]::GetInvalidFileNameChars()) { $i=([int]$c); "{0,3:d}  {1,2:x2}  {2,1}" -f $i,$i,$c }

尝试

[System.IO.Path]::GetInvalidFileNameChars() | ForEach-Object {'{0:X2}' -f [int]$_ }

除了缺少 foreach,GetInvalidFileNameChars() 输出字符,

[System.IO.Path]::GetInvalidFileNameChars() | foreach { $_.gettype() }

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Char                                     System.ValueType
True     True     Char                                     System.ValueType

并且 tostring('x2') 方法用于整数(或字节)。

(1).tostring('x2')
01

您可以通过省略括号来获得定义。第二个是您要 运行.

(1).tostring

OverloadDefinitions
-------------------
string ToString()
string ToString(string format)
string ToString(System.IFormatProvider provider)
string ToString(string format, System.IFormatProvider provider)
string IConvertible.ToString(System.IFormatProvider provider)
string IFormattable.ToString(string format, System.IFormatProvider formatProvider)

所以(因为 .tostring 的优先级高于 [int],我们需要额外的括号)(我在 osx 所以只有 2 个结果。)

[System.IO.Path]::GetInvalidFileNameChars() | foreach { ([int]$_).tostring('x2') }
00
2f

如果你想要 format-h​​ex,请升级你的 powershell。

和上一个一样。该方法适用于整数:

ForEach ($c in [System.IO.Path]::GetInvalidFileNameChars()) { 
  echo ([int]$c).ToString("X2") }

Int32.ToString方法:https://docs.microsoft.com/en-us/dotnet/api/system.int32.tostring?view=netframework-4.8#System_Int32_ToString_System_String_

What I would like is get their hex (or decimal) code.

因为 [System.IO.Path]::GetInvalidFileNameChars() returns [char[]][char] 个实例的数组 ([])),你可以直接转换它数组到 [int[]] 以获得 .NET [char] 实例代表的 UTF-16 代码单元的 Unicode 代码点;默认情况下,它们 呈现为 十进制 数字 :

PS> [int[]] [System.IO.Path]::GetInvalidFileNameChars()

34
60
62
124
0
...

要获取 十六进制 数字(作为字符串),通过管道传输到 ForEach-Object 并通过传递的格式字符串格式化每个数字到 -f,PowerShell 的字符串格式化运算符;例如,将每个代码点格式化为 0x 前缀的十六进制。 0-left-padded 到 2 位数字的数字(PSv4+ 语法;在 PSv3- 中,管道改为 ForEach-Object,如 中那样,这会更慢):

PS> [System.IO.Path]::GetInvalidFileNameChars().ForEach({ '0x{0:x2}' -f [int] $_ })

0x22
0x3c
0x3e
0x7c
0x00
...