PowerShell 5.1如何原样打印含特殊符号的JSON数组值?
PowerShell 5.1中JSON数组原样输出解决方案
问题背景
环境:PowerShell 5.1
目标JSON片段:
"MyAddresses": ["email100@my.com", "email200@my.com", "email300@my.com", "email400@my.com"],
现有脚本可获取该键对应的值,但输出时丢失了括号、双引号和逗号,无法保留原始JSON格式。
问题原因
现有脚本使用ConvertFrom-Json将JSON内容转换为PowerShell对象,数组类型的属性在直接拼接字符串输出时,会被PowerShell自动展开为空格分隔的纯文本,导致原始JSON格式丢失。
解决方案
方案一:将数组转回JSON格式
修改脚本中提取并输出值的部分,用ConvertTo-Json把PowerShell数组重新转换成JSON字符串,配合-Compress参数可以输出紧凑的单行格式:
修改后的完整脚本:
# Define the path to the JSON file on the remote computers $jsonFilePath = "C:\mydata.json" # Script block to run on each remote computer $scriptBlock = { param ($jsonFilePath) try { # Read the JSON file content $jsonContent = Get-Content -Path $jsonFilePath -Raw | ConvertFrom-Json # 将提取的数组转回JSON格式 $receiverAddress = $jsonContent.Notification.ReceiverAddresses | ConvertTo-Json -Compress # Output the value Write-Output "******************************** $($env:COMPUTERNAME) - START OF DATA ********************************************" Write-Output "ReceiverAddress: $receiverAddress" Write-Output "******************************* $($env:COMPUTERNAME) - END OF DATA *********************************************" } catch { Write-Output "Error on $($env:COMPUTERNAME): $_" } } # Define the list of remote computers $computers = @" server1 server2 "@ -split [Environment]::NewLine # Run the script block on each remote computer in parallel $jobs = Invoke-Command -ComputerName $computers -ScriptBlock $scriptBlock -ArgumentList $jsonFilePath -AsJob # Wait for all jobs to complete $jobs | ForEach-Object { $_ | Wait-Job } # Retrieve and display the results $jobs | ForEach-Object { try { $result = Receive-Job -Job $_ Write-Output $result } catch { Write-Output "Failed to retrieve job results for $($_.Location): $_" } finally { Remove-Job -Job $_ } }
方案二:直接提取JSON片段(不转换对象)
如果不需要处理JSON中的其他内容,也可以用正则表达式直接从原始JSON字符串中提取目标键的数组部分,避免对象转换的步骤:
修改后的脚本块关键部分:
try { # 读取原始JSON字符串 $jsonRawContent = Get-Content -Path $jsonFilePath -Raw # 用正则匹配提取ReceiverAddresses的数组内容 if ($jsonRawContent -match '"ReceiverAddresses":\s*(\[.*?\])') { $receiverAddress = $matches[1] } else { $receiverAddress = "未找到ReceiverAddresses键" } # Output the value Write-Output "******************************** $($env:COMPUTERNAME) - START OF DATA ********************************************" Write-Output "ReceiverAddress: $receiverAddress" Write-Output "******************************* $($env:COMPUTERNAME) - END OF DATA *********************************************" } catch { Write-Output "Error on $($env:COMPUTERNAME): $_" }
内容的提问来源于stack exchange,提问作者Rod
相关产品推荐
相关产品推荐

