2014-10-06 151 views
0

使用powershell和Im试图将其转换为JSON,但问题是需要将所有斜线加倍。所以\需要变成\\\\需要在输出中被\\\\取代。即时通讯使用PowerShell中使用以下脚本:使用powershell输出斜杠

$array = @() 
echo "{"; echo '"data":['; (get-counter "\Processor(*)\% Idle Time").CounterSamples.Path | %{ $array += '{ "{#CPUID}":"'+ $_.TrimStart("$LowerCaseComputerName") } 
for($i = 0; $i -lt $array.Length - 1; $i++){ $array[$i] + '"},' } 
$array[$array.Length - 1] + '"}' 
echo "]" ; echo "}"; 

和输出即时得到是正确的,除了反斜杠需要加倍:

{ 
"data":[ 
{ "{#CPUID}":"\\aaronmartinez\processor(0)\% idle time"}, 
{ "{#CPUID}":"\\aaronmartinez\processor(1)\% idle time"}, 
{ "{#CPUID}":"\\aaronmartinez\processor(2)\% idle time"}, 
{ "{#CPUID}":"\\aaronmartinez\processor(3)\% idle time"}, 
{ "{#CPUID}":"\\aaronmartinez\processor(4)\% idle time"}, 
{ "{#CPUID}":"\\aaronmartinez\processor(5)\% idle time"}, 
{ "{#CPUID}":"\\aaronmartinez\processor(6)\% idle time"}, 
{ "{#CPUID}":"\\aaronmartinez\processor(7)\% idle time"}, 
{ "{#CPUID}":"\\aaronmartinez\processor(_total)\% idle time"} 
] 
} 
+0

它只是一个字符串,基本上不会捕获字符串的回应,然后做一个简单的字符串替换'' - > \\''? – 2014-10-06 21:43:44

回答

1

所有你需要做的是一个简单的-Replace '\\','\\',并完成它。第一个'\\'是正则表达式,因此\转义为\\。它应该是这样的:

$array = @() 
"{" 
'"data":[' 
(get-counter "\Processor(*)\% Idle Time").CounterSamples.Path | %{ $array += '{ "{#CPUID}":"'+ $_.TrimStart("$LowerCaseComputerName") } 
for($i = 0; $i -lt $array.Length - 1; $i++){ ($array[$i] -replace '\\','\\')+ '"},' } 
($array[$array.Length - 1] -Replace '\\','\\')+ '"}' 
"]" 
"}" 

编辑:虽然这不回答你的问题,在我看来,一个更好的解决办法是形成正确的对象和使用ConvertTo JSON的cmdlet的。

$object = [pscustomobject][ordered]@{'Data'[email protected]()} 
(get-counter "\Processor(*)\% Idle Time").CounterSamples.Path | %{ $Object.data += [pscustomobject]@{'#CPUID'= $_.TrimStart("$LowerCaseComputerName") }} 
$object | ConvertTo-Json 

这给你相同的结果,我很确定。

1

如果您在PowerShell v3中,则有一个用于将数据结构转换为JSON格式的cmdlet ConvertTo-Json。你可能会发现比这样的手工制作更容易。 {字符使字符串格式非常混乱。