排序对象 - 唯一

Sort-Object -Unique

我正在制作一个脚本,从特定位置收集所有子键并将 REG_BINARY 键转换为文本,但由于某些原因我无法删除重复结果或按字母顺序对它们进行排序。

PS:不幸的是,我需要可以从命令行执行的解决方案。

代码:

$List = ForEach ($i In (Get-ChildItem -Path 'HKCU:SOFTWARE[=10=]0' -Recurse)) {$i.Property | ForEach-Object {([System.Text.Encoding]::Unicode.GetString($i.GetValue($_)))} | Select-String -Pattern ':'}; ForEach ($i In [char[]]'ABCDEFGHIJKLMNOPQRSTUVWXYZ') {$List = $($List -Replace("$i`:", "`n$i`:")).Trim()}; $List | Sort-Object -Unique

Test.reg:

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\SOFTWARE[=11=]0\Test1]
"HistorySZ1"="Test1"
"HistoryBIN1"=hex:43,00,3a,00,5c,00,54,00,65,00,73,00,74,00,5c,00,44,00,2e,00,\
  7a,00,69,00,70,00,5c,00,00,00,43,00,3a,00,5c,00,54,00,65,00,73,00,74,00,5c,\
  00,43,00,2e,00,7a,00,69,00,70,00,5c,00,00,00,43,00,3a,00,5c,00,54,00,65,00,\
  73,00,74,00,5c,00,42,00,2e,00,7a,00,69,00,70,00,5c,00,00,00,43,00,3a,00,5c,\
  00,54,00,65,00,73,00,74,00,5c,00,41,00,2e,00,7a,00,69,00,70,00,5c,00,00,00


[HKEY_CURRENT_USER\SOFTWARE[=11=]0\Test2]
"HistorySZ2"="Test2"
"HistoryBIN2"=hex:4f,00,3a,00,5c,00,54,00,65,00,73,00,74,00,5c,00,44,00,2e,00,\
  7a,00,69,00,70,00,5c,00,00,00,43,00,3a,00,5c,00,54,00,65,00,73,00,74,00,5c,\
  00,43,00,2e,00,7a,00,69,00,70,00,5c,00,00,00,44,00,3a,00,5c,00,54,00,65,00,\
  73,00,74,00,5c,00,42,00,2e,00,7a,00,69,00,70,00,5c,00,00,00,41,00,3a,00,5c,\
  00,54,00,65,00,73,00,74,00,5c,00,41,00,2e,00,7a,00,69,00,70,00,5c,00,00,00

经过多次尝试,我发现必须使用Split命令来进行分行,这样才能对结果进行整理。

{$List = ($List -Replace("$i`:", "`n$i`:")) -Split("`n")}

字节数组中编码的路径字符串用 NUL 个字符(代码点 0x0)分隔。

因此,您需要将您的字符串按此字符拆分成一个数组的各个路径,然后您可以对其进行操作比如Sort-Object:

您可以在可扩展的 PowerShell 字符串中将 NUL 字符表示为 "`0",或者 - 在 regex 中传递给 -split operator - [=17=]:

# Convert the byte array stored in the registry to a string.
$text = [System.Text.Encoding]::Unicode.GetString($i.GetValue($_))

# Split the string into an *array* of strings by NUL.
# Note: -ne '' filters out empty elements (the one at the end, in your case).
$list = $text -split '[=10=]' -ne ''

# Sort the list.
$list | Sort-Object -Unique