如何用PowerShell每日替换JSON文件中LogDirectoryPath的日期
Great question! Here's a step-by-step solution to automate updating the LogDirectoryPath date in your JSON config using a PowerShell script and scheduled task:
Solution
Step 1: Create the PowerShell Script
First, make a script that will modify your JSON file with today's date. Save this as Update-LogPath.ps1 (pick a location that's easy to reference, like C:\Scripts\Update-LogPath.ps1):
# Define paths $jsonFilePath = "C:\path\to\your\config.json" # Replace with your actual JSON file path $baseLogPath = "C:\log\" # Get today's date in yyyy-MM-dd format $todayDate = Get-Date -Format "yyyy-MM-dd" # Read and parse the JSON file $jsonContent = Get-Content -Path $jsonFilePath -Raw | ConvertFrom-Json # Update the LogDirectoryPath with today's date $jsonContent.EngineConfiguration.Components[0].Parameters.LogDirectoryPath = "$baseLogPath$todayDate" # Convert back to JSON and save (use -Depth to preserve nested structure) $jsonContent | ConvertTo-Json -Depth 3 | Set-Content -Path $jsonFilePath -Encoding UTF8
Notes about the script:
- Replace
$jsonFilePathwith the actual path to your JSON configuration file. - The
-Depth 3parameter ensures the nested JSON structure is preserved (your config has 3 levels of nesting:EngineConfiguration→Components→Parameters). - Test this script manually first to confirm it updates the JSON correctly!
Step 2: Create a Scheduled Task with PowerShell
Next, use PowerShell to create a daily scheduled task that runs the script. Run PowerShell as Administrator for this step:
# Define task settings $taskName = "Update CloudWatch Log Path Daily" $scriptPath = "C:\Scripts\Update-LogPath.ps1" # Match the path to your script $trigger = New-ScheduledTaskTrigger -Daily -At 00:00 # Runs at midnight daily $action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass -File `"$scriptPath`"" # Register the task (runs with highest privileges, whether user is logged on or not) Register-ScheduledTask -TaskName $taskName -Trigger $trigger -Action $action -RunLevel Highest -User "NT AUTHORITY\SYSTEM" -Force
Key details:
- The
-ExecutionPolicy Bypassensures PowerShell allows running the script (adjust if your environment has stricter policies). - Using
NT AUTHORITY\SYSTEMas the user ensures the task runs even if no one is logged on, and has sufficient permissions (verify this account can write to your JSON file and read the script). - Adjust the
-At 00:00time to whenever you want the update to happen (e.g.,-At 02:00for 2 AM).
Verification
- Run the script manually once to check if the JSON's
LogDirectoryPathupdates to today's date. - Check the Task Scheduler to confirm the task exists under the "Task Scheduler Library".
- You can test the task by right-clicking it and selecting "Run" to ensure it executes without errors.
内容的提问来源于stack exchange,提问作者Ankita13
相关产品推荐
相关产品推荐

