🎓 A1Learner
🔍
0 of 46 lessons completed

PowerShell Tool Configuration

Tool configuration is reading a tool's settings from a file instead of writing them into the code. A JSON file holds the settings in text, and the tool reads them each time it runs.

Read settings from a JSON file

Write the settings as JSON text in a file. Read the file and turn it into an object, then print its properties.

Set-Content -Path "config.json" -Value '{"tool":"backup","folder":"data"}'
$config = Get-Content -Path "config.json" -Raw | ConvertFrom-Json
$config.tool
$config.folder

Read a nested group of settings

A group inside the settings is reached through its name. Print one value from inside the group.

Set-Content -Path "config.json" -Value '{"backup":{"folder":"data","count":3}}'
$config = Get-Content -Path "config.json" -Raw | ConvertFrom-Json
$config.backup.folder
$config.backup.count

Fall back to a default for a missing setting

Check whether a setting is empty before using it. Use a fixed default when the file does not name the setting.

Set-Content -Path "config.json" -Value '{"tool":"backup"}'
$config = Get-Content -Path "config.json" -Raw | ConvertFrom-Json
if ($null -eq $config.retries) { "Retries: 3" } else { "Retries: " + $config.retries }

Example

Set-Content -Path "config.json" -Value '{"tool":"backup","folder":"data","enabled":true}'
$config = Get-Content -Path "config.json" -Raw | ConvertFrom-Json
$retries = 3
if ($null -ne $config.retries) { $retries = $config.retries }
"Tool: " + $config.tool
"Folder: " + $config.folder
"Enabled: " + $config.enabled
"Retries: " + $retries

Key points

  • JSON text: JSON is a text format that stores settings as named values.
  • ConvertFrom-Json: ConvertFrom-Json turns JSON text into an object whose properties hold the settings.
  • Get-Content -Raw: Get-Content with -Raw reads a whole file as one piece of text.
  • Nested settings: A setting can hold its own group of settings, reached one level at a time.
  • Missing setting: A setting that is not in the file reads as an empty value, so the tool can fall back to a default.

In this example, the settings file names a tool, a folder, and a switch value. The script reads the file and turns it into an object. It keeps the default of 3 for retries because the file does not name that setting. Then it prints each setting as a plain value.

Note

A configuration file lets one tool behave differently without changing its code.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A tool reads its settings from a JSON file. Which command turns the JSON text from the file into an object?