Replace a value in a json using powershell

独自空忆成欢 提交于 2021-01-28 05:50:38

问题


I have a json file with the following content -

{
"IsEnabled": true,
"EngineConfiguration": {
    "PollInterval": "00:00:15",
    "Components": [{
        "Id": "Logs",
        "FullName": "AWS.EC2.Windows.CloudWatch.CustomLog.CustomLogInputComponent,AWS.EC2.Windows.CloudWatch",
        "Parameters": {
            "LogDirectoryPath": "C:\\log\\2018-05-25",
            "TimestampFormat": "yyyy-MM-dd HH:mm:ss",
            "Encoding": "UTF-8",
            "Filter": "",
            "CultureName": "en-US",
            "TimeZoneKind": "UTC",
            "LineCount": "1"
        }
    }]
  }
}

I want to replace this date(mentioned in LogDirectoryPath) everyday using a managed task using powershell.

Can someone please give the easiest way to replace this everyday using powershell?


回答1:


This script will help you to update log directory.

Steps:

  1. Get content of json file.
  2. Update attribute value if exists. $JsonData.update | % {if(...)
  3. Save content in same file.

Script:

$JsonData = Get-Content $JsonFilePath -raw | ConvertFrom-Json

$JsonData.update | % { if($JsonData.engineconfiguration.Components.Parameters.LogDirectoryPath)
                            {
                                $JsonData.engineconfiguration.Components.Parameters.LogDirectoryPath = "C:\log\$(Get-Date -Format 'yyyy-MM-dd')"
                            }
                        }

$JsonData | ConvertTo-Json -Depth 4  | set-content $JsonFilePath 


来源:https://stackoverflow.com/questions/50521035/replace-a-value-in-a-json-using-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!