使用base64编码的PowerShell问题

时间:2018-12-04 18:51:00

标签: powershell

我需要将逗号分隔的值(.csv)数组转换为如下所示的JSON:

$traits = New-Object PSObject
$file = New-Object PSObject
$file | Add-Member -Type NoteProperty -Name file_name -Value "file.csv"
$file | Add-Member -Type NoteProperty -Name content -Value $([Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes(($domain.GPOs | ConvertTo-Csv))))
$traits | Add-Member -Type NoteProperty -Name group-policies -Value $file

我正在使用以下内容:

#TYPE Selected.System.Xml.XmlElement
"Name","GUID","Linked To","Computer Settings","User Settings"
"Autodiscover - Shared Namespace","249b1923-523a-40b6-9180-cc2727414b9b","@{OU Name=servers; OU Path=domain.local/location/servers; Enabled=true; Enforced=false}","@{Enabled=true; Settings=}","@{Enabled=true; Settings=}"

似乎“内容”的内容编码不正确。为了进行故障排除,我将内容复制到www.freeformatter.com/base64-encoder.html,发现它们不匹配。

我想念什么?

编辑:这是.csv的内容。这就是我粘贴到https://www.freeformatter.com/base64-encoder.html#ad-output中的内容:

IwBUAFkAUABFACAAUwBlAGwAZQBjAHQAZQBkAC4AUwB5AHMAdABlAG0ALgBYAG0AbAAuAFgAbQBsAEUAbABlAG0AZQBuAHQAIAAiAE4AYQBtAGUAIgAsACIARwBVAEkARAAiACwAIgBMAGkAbgBrAGUAZAAgAFQAbwAiACwAIgBDAG8AbQBwAHUAdABlAHIAIABTAGUAdAB0AGkAbgBnAHMAIgAsACIAVQBzAGUAcgAgAFMAZQB0AHQAaQBuAGcAcwAiACAAIgBBAHUAdABvAGQAaQBzAGMAbwB2AGUAcgAgAC0AIABTAGgAYQByAGUAZAAgAE4AYQBtAGUAcwBwAGEAYwBlACIALAAiADIANAA5AGIAMQA5ADIAMwAtADUAMgAzAGEALQA0ADAAYgA2AC0AOQAxADgAMAAtAGMAYwAyADcAMgA3ADQAMQA0AGIAOQBiACIALAAiAEAAewBPAFUAIABOAGEAbQBlAD0AcwBlAHIAdgBlAHIAcwA7ACAATwBVACAAUABhAHQAaAA9AGQAbwBtAGEAaQBuAC4AbABvAGMAYQBsAC8AbABvAGMAYQB0AGkAbwBuAC8AcwBlAHIAdgBlAHIAcwA7ACAARQBuAGEAYgBsAGUAZAA9AHQAcgB1AGUAOwAgAEUAbgBmAG8AcgBjAGUAZAA9AGYAYQBsAHMAZQB9ACIALAAiAEAAewBFAG4AYQBiAGwAZQBkAD0AdAByAHUAZQA7ACAAUwBlAHQAdABpAG4AZwBzAD0AfQAiACwAIgBAAHsARQBuAGEAYgBsAGUAZAA9AHQAcgB1AGUAOwAgAFMAZQB0AHQAaQBuAGcAcwA9AH0AIgA=

Powershell输出以下内容:

I1RZUEUgU2VsZWN0ZWQuU3lzdGVtLlhtbC5YbWxFbGVtZW50DQoiTmFtZSIsIkdVSUQiLCJMaW5rZWQgVG8iLCJDb21wdXRlciBTZXR0aW5ncyIsIlVzZXIgU2V0dGluZ3MiDQoiQXV0b2Rpc2NvdmVyIC0gU2hhcmVkIE5hbWVzcGFjZSIsIjI0OWIxOTIzLTUyM2EtNDBiNi05MTgwLWNjMjcyNzQxNGI5YiIsIkB7T1UgTmFtZT1zZXJ2ZXJzOyBPVSBQYXRoPWRvbWFpbi5sb2NhbC9sb2NhdGlvbi9zZXJ2ZXJzOyBFbmFibGVkPXRydWU7IEVuZm9yY2VkPWZhbHNlfSIsIkB7RW5hYmxlZD10cnVlOyBTZXR0aW5ncz19IiwiQHtFbmFibGVkPXRydWU7IFNldHRpbmdzPX0i

网站吐出:

{{1}}

1 个答案:

答案 0 :(得分:2)

存在三个(潜在)问题:

  • 字符编码

    • www.freeformatter.com将Base64编码基于输入字符串的 UTF-8 编码。
    • 您的PowerShell代码使用UTF-16LE(“ Unicode”)编码作为基础;如果您要使用UTF-8,请改用[System.Text.Encoding]::UTF8.GetBytes()
  • 换行符样式(行尾)

    • 粘贴在www.freeformatter.com上的文本中的换行符将悄悄地转换为Windows风格的CRLF换行符,而您的输入可能则具有Unix风格的仅LF换行符。
  • 换行符丢失

    • 您要将输出从ConvertTo-Csv(它是字符串的数组)传递到[System.Text.Encoding]::Unicode.GetBytes(),后者需要一个 single 字符串。在PowerShell的过程中, stringify 数组,这意味着其元素以空格作为分隔符进行连接,因此原始换行符被空格替换,从而导致不同的编码输出。
    • 因此,使用($domain.GPOs | ConvertTo-Csv)代替($domain.GPOs | ConvertTo-Csv) -join [Environment]::NewLine(使用平台合适的换行序列;或者,显式使用"`n""`r`n";此外,您可能想要追加 trailing 换行符)。