json - 如何将PowerShell动态变量值传递给JSON

标签 json powershell variables

我正在一个项目中,使基于Windows的计算机运行计划的powershell脚本,该脚本将以JSON结构化数据文件的形式发布主机状态。目的是使相同的脚本能够在任何Windows计算机上运行,​​而不必手动为脚本将放置在每个服务器上的变量值键入主机名,IP地址等。

$hn = hostname
$ip = ipconfig
echo $hn
echo $ip
$params = '{
"host": "$(hn)",
"service": "APP_NAME",
"annotation": "Service is looking dope!",
“ip": "$(ip)"
}'

Invoke-WebRequest -Uri http://yoursite.com:5550/ -Method POST -ContentType "application/json" -Body $params
#Invoke-RestMethod -Uri http://yoursite.com:5550/ -Method POST -ContentType "application/json" -Body $params

我最终得到以下输出的变化(注意主机名和ip变量保持不变):
HOSTNAME1
1.1.1.1
'{
"host": "$(hn)",
"service": "APP_NAME",
"annotation": "Service is looking dope!",
“ip": "$(ip)"
}'

我希望输出如下所示:
HOSTNAME1
1.1.1.1
'{
"host": "HOSTNAME1",
"service": "APP_NAME",
"annotation": "Service is looking dope!",
“ip": "1.1.1.1"
}'

我尝试了以下网站中提到的建议:
  • How to make a POST request using Powershell if body have a parameter @type
  • https://powershell.org/forums/topic/how-to-make-a-post-request-using-powershell-if-body-have-a-parameter-type/
  • https://www.sapien.com/blog/2018/03/22/storing-powershell-variables-in-external-files/comment-page-1/
  • https://hazzy.techanarchy.net/winadmin/windows/windows-powershell-elk-log-wash/

  • 我尝试使用双引号和单引号的组合,并使用@ {},@'{,并附加到参数即“param + =”或“param = +”。运气不好的方法,或者我可能错过了一些东西。

    我能够从转换为JSON计数器部分的单个命令中获取详细信息,即
    Get-WmiObject -Class Win32_ComputerSystem -Property Name | ConvertTo-Json
    

    但是我很难将两个不同的信息结合到一个json文件中。另外,我很难提取特定信息并填充json文件,即
    (Get-WmiObject -Class Win32_ComputerSystem -Property Name).Name | ConvertTo-Json
    

    如果我误用了任何术语或未遵循任何发布准则,我深表歉意。如果我违反了任何条件,请告知我,我将进行必要的更改以遵守这些条件。如果我不清楚或错过任何重要信息,我深表歉意。在此先感谢您,我们将不胜感激。

    最佳答案

    您需要反转JSON字符串中的引号。单撇号内的任何内容都不会解析为包含可计算的内容。或者,也可以使用如下所示的Here-String:

    $params = @"
    {
    "host": "$hn",
    "service": "APP_NAME",
    "annotation": "Service is looking dope!",
    "ip": "$ip"
    }
    "@
    

    PS :(可能)最好通过Powershell方式Get-NetIPAddress (params)| Select IPAddress来获取IP地址。

    关于json - 如何将PowerShell动态变量值传递给JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51529457/

    相关文章:

    powershell - 为什么安全字符串需要force和AsPlainText

    javascript - 通过 HTML 更改脚本中的变量

    php - 在 PHP 中,是否有一种将变量与多个值进行比较的捷径?

    json - 用于中间/临时存储的 Azure cosmos db 与 blob 存储

    javascript - 无法通过 XMLHttpRequest 发送大型 json 数据 - javascript

    c# - JSON.Net 自定义合约序列化和集合

    c# - 如何在 PowerShell 中创建具有行为(方法)的真实对象?

    c# - JsonPropertyAttribute 在派生类中的私有(private)属性上被忽略

    regex - 适用于mm-dd-yyyy的Powershell正则表达式

    javascript - 我可以为多个变量分配相同的值,而每个变量/赋值没有一行吗?