🎓 A1Learner
🔍
0 of 46 lessons completed

PowerShell Configuration Data

Configuration data is a hashtable that lists the files you want and the content each file should hold. One function reads the data and sets every file from it.

One hashtable holds many files

Each key is a file name, and each value is its content. The order stays fixed because the hashtable is ordered.

$config = [ordered]@{ "a.txt" = "apple"; "b.txt" = "berry" }
$config["a.txt"]
($config.Keys -join ", ")

One function sets every file

The function walks each key and writes its value. Two files appear with the right content.

function Set-ConfiguredFiles { param($Config) foreach ($name in $Config.Keys) { Set-Content -Path $name -Value $Config[$name] } }
$config = [ordered]@{ "a.txt" = "apple"; "b.txt" = "berry" }
Set-ConfiguredFiles -Config $config
Get-ChildItem -Filter *.txt | Sort-Object Name | Select-Object -ExpandProperty Name

Change the data, not the function

A new value in the data gives a new file content. The function itself does not change.

function Set-ConfiguredFiles { param($Config) foreach ($name in $Config.Keys) { Set-Content -Path $name -Value $Config[$name] } }
$config = [ordered]@{ "a.txt" = "apple" }
Set-ConfiguredFiles -Config $config
$config["a.txt"] = "apricot"
Set-ConfiguredFiles -Config $config
Get-Content -Path "a.txt"

Example

function Set-ConfiguredFiles { param($Config) foreach ($name in $Config.Keys) { Set-Content -Path $name -Value $Config[$name] } }
$config = [ordered]@{ "a.txt" = "apple"; "b.txt" = "berry"; "c.txt" = "cherry" }
Set-ConfiguredFiles -Config $config
foreach ($name in $config.Keys) { Get-Content -Path $name }

Key points

  • Configuration data: a hashtable that describes the end result for many files at once.
  • Key: the file name in the hashtable.
  • Value: the content that file should hold.
  • Data driven: changing the data changes the result, while the function stays the same.

In this example, the script stores three file names and contents in an ordered hashtable, calls the function once, and then reads each file back in order.

Note

This is still plain PowerShell, not the DSC engine.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

You change only the hashtable and run the function again. What changes?