Replace date and save json not working

Himanshuk 161 Reputation points
2021-02-16T16:02:14.877+00:00

How to replace target date to today date using powershell
I have tried out all find and replace technique but date is not saved

$today='{:0:yyyy-MM-dd}' -f (get-date)
$file="c:\temp\sample.json";(gc $file| convertfrom-json)|
Foreach-Object {$_ -replace ""target" : (\d+)/(\d+)/(\d+)", ""target" : $today"} | Set-Content $file

code in the file c:\temp\sample.json is

{ 
 "response": [
   {
 "id":"11",
 "acc":"me",
 "dateMain":{
        "start": "2020-22-01",
        "target": "2020-22-02"
                }
   },
 "majorreldate" : [
 {
 "start": "2020-22-01",
 "target": "2020-22-02"
 }
 ],
 "minorreldate" :{
 "start": "2020-22-01",
 "target": "2020-22-02"
 }
  ]
}
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,580 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 47,466 Reputation points
    2021-02-16T19:52:04.077+00:00

    It would be nice if the JSON you posted was in the correct format! Also, there's an extra ":" in your date format string.

    Treating the data as a plain text file, this will work:

    $x = Get-Content C:\junk\j.json -Raw
    $today='{0:yyyy-MM-dd}' -f (get-date)
    $y = $x -creplace '"target": "\d\d\d\d-\d\d-\d\d"', """target"": ""$today"""
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Ian Xue 38,631 Reputation points Microsoft Vendor
    2021-02-17T05:10:01.517+00:00

    Hi,

    Hope this works for you

    $today='{0:yyyy-MM-dd}' -f (get-date)  
    $file='c:\temp\sample.json'  
    (Get-Content $file) -replace '(?<="target":\s+")\d{4}-\d{2}-\d{2}',$today  
    

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.