0

I've got a JSON file containing configuration for my PS app.

This data is changed often by the script. The problem is that I am editing the variable containing the JSON data, imported using ConvertFrom-JSON.

I want it so that the PS edits directly the JSON file, so that if a force termination happens, the JSON is up-to-date with the latest conf changes.

Let me know if I'm clear and I'll edit my question if you need more details.

Silloky
  • 147
  • 13
  • 1
    (Unrelated to PowerShell) [There's no way to inject data into the middle of a file, unfortunately.](https://stackoverflow.com/a/29601418/1701026) – iRon Jun 20 '23 at 08:07
  • Basically you have to rewrite the whole JSON file on every change to a configuration setting. – zett42 Jun 20 '23 at 08:14
  • 2
    What kind of termination is expected? If you just need to handle script-terminating errors, but not process termination from the outside (e. g. using task manager), then you could make sure the JSON file is always saved by using a `try` / `finally` block. This would be much more efficient than rewriting the JSON on every configuration change. – zett42 Jun 20 '23 at 08:25
  • @zett42 ok... would you mind posting an answer explaining that try...finally block more in detail please ? – Silloky Jun 20 '23 at 09:49
  • @zett42 termination such as forced ACPI shutdown for example – Silloky Jun 20 '23 at 09:54
  • "*would you mind posting an answer explaining*". To properly answer this issue description, it would require a [mcve] showing (a part -or an example- of) your JSON input file and how you currently capture a "*forced ACPI shutdown*" termination. – iRon Jun 20 '23 at 11:27
  • In case of system shutdown `try` / `finally` won't work. You need to register for shutdown event. https://stackoverflow.com/a/10187296/7571258 -- fairly old post, I don't know if this still works. – zett42 Jun 20 '23 at 11:28
  • create a variable calculation function containing data in json format. In addition, the json must be overwritten before returning data from the function. – rinat gadeev Jun 20 '23 at 11:34

0 Answers0