【问题标题】:Sort-Object -Unique排序对象-唯一
【发布时间】:2021-12-02 10:23:09
【问题描述】:

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

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

代码:

$List = ForEach ($i In (Get-ChildItem -Path 'HKCU:SOFTWARE\000' -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\000\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\000\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

【问题讨论】:

    标签: powershell command-line


    【解决方案1】:

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

    因此,您需要通过该字符将字符串拆分成单个路径的数组,然后您可以在其上执行诸如Sort-Object之类的操作:

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

    # 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 '\0' -ne ''
    
    # Sort the list.
    $list | Sort-Object -Unique
    

    【讨论】:

      【解决方案2】:

      经过多次尝试,我发现有必要使用Split命令来使行换行,从而能够组织结果。

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

      【讨论】:

        猜你喜欢
        • 2017-10-13
        • 1970-01-01
        • 2017-08-26
        • 2021-02-18
        • 2022-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多