PowerShell by Patrik

Extract the environment Node Using Multiline Regex

When JSON Parsing Is Not Possible

Sometimes configuration files are not valid JSON. They may contain comments or formatting issues. In such cases, ConvertFrom-Json will fail. When that happens, you can extract the environment section using a multiline regular expression.

Small example file:

{
  "application": "SampleApp",
  "environment": {
    "name": "Production",
    "debug": false
  },
  // comment
  "logging": "Information"
}

PowerShell Regex solution:

$content = Get-Content "appsettings.json" -Raw

if ($content -match '(?s)"environment"\s*:\s*\{.*?\}') {
    $matches[0]
}

Explanation:

  • (?s) allows the dot to match across multiple lines
  • .*? ensures non-greedy matching
  • The pattern extracts the full environment object

This method works well when:

  • The structure is simple
  • You need one known section
  • Full JSON parsing is not possible

Important: Regex does not fully understand nested JSON structures. Use it only when parsing cannot be used.

For Azure RunCommand scenarios with limited console output, this method provides a focused and practical solution.

regex
powershell
azure
textprocessing
automation

Comments