我正在使用从https://curl.haxx.se/
下载的外部curl命令我正在尝试使用curl命令将一些信息写入在我的机器上本地运行的elasticsearch
我正在通过convertto-json运行信息,以确保在将数据传递给外部curl命令之前正确格式化数据
我遇到的问题是,任何带有空格的字段都会被卷曲立即释放出来,意外的输入结束错误,删除字段数据中的空格可以使其处于正常状态。
$curlExe = "h:\powershell\esb\elastic\curl\curl.exe"
function global:elasticcall ([string] $elasticdata)
{
$elasticoutput = "h:\powershell\esb\elastic\elastic.txt"
$elastichost="http://localhost:9200/newtest4/filecopy/?pretty"
$elasticheader="content-type: application/json"
$elamethod="POST"
$jsonelasticdata = $elasticdata | ConvertTo-Json -Compress
$curlargs = $elastichost,
'-X',$elamethod,
'-d',$jsonelasticdata,
'-H',$elasticheader
write-host "Curl arguements in the entire string : " $curlargs
& $curlexe @curlargs
$elasticdata | Out-File $elasticoutput -Append
}
$timereceived="randomness"
$timesentconv="randomness2"
$name="testingspaces.txt"
$curlstatus=0
$elasticbody = '{"timereceived":"' + $timereceived + '","timesent":"' + $timesentconv + '","Filename":"' + $name + '","Status":"' + $curlstatus + '"}'
elasticcall $elasticbody
将变量$ name更改为“testing spaces.txt”会生成错误。
答案 0 :(得分:0)
您正在使用已手动尝试格式化为json的当前字符串$elasticbody
。
$timereceived = "randomness"
$timesentconv = "randomness2"
$name = "testing spaces.txt"
$curlstatus = 0
$elasticbody = '{"timereceived":"' + $timereceived + '","timesent":"' + $timesentconv + '","Filename":"' + $name + '","Status":"' + $curlstatus + '"}'
$elasticbody | ConvertTo-Json -Compress
这将返回以下内容,您可以看到文件名周围没有引号,字符串本身用引号括起来。
结果:"\"timereceived\":\"randomness\",\"timesent\":\"randomness2\",\"Filename\":\"testing spaces.txt\",\"Status\":\"0\"}"
你应该尝试做一些清单:
$GLOBAL:curlExe = "h:\powershell\esb\elastic\curl\curl.exe"
function global:elasticcall {
param (
$timereceived,
$timesentconv,
$name,
$curlstatus,
$elasticoutput = "h:\powershell\esb\elastic\elastic.txt",
$elastichost = "http://localhost:9200/newtest4/filecopy/?pretty",
$elasticheader = "content-type: application/json",
$elamethod = "POST"
)
$elasticdata = @{
timereceived = $timereceived
timesent = $timesentconv
Filename = $name
Status = $curlstatus
}
$jsonelasticdata = $elasticdata | ConvertTo-Json -Compress
$curlargs = $elastichost,
'-X', $elamethod,
'-d', $jsonelasticdata,
'-H', $elasticheader
write-host "Curl arguements in the entire string : " $curlargs
& $curlexe @curlargs
$elasticdata | Out-File $elasticoutput -Append
}
global:elasticcall -timereceived 'randomness' -timesentconv 'randomness2' -name 'testing spaces.txt' -curlstatus 0
您接受变量作为参数,并使用函数内的ConvertTo-Json
对其进行格式化。它应该正确处理字符串中的空格。