🎓 A1Learner
🔍
0 of 46 lessons completed

PowerShell Test/Set Pattern

The Test/Set pattern is a pair of plain PowerShell functions that check a result and fix it. One function tests the current result, and the other sets it right.

Test the current result

The Test function compares the file with the desired value. It returns True when they match.

function Test-DesiredContent { param([string]$Path, [string]$Desired) (Get-Content -Path $Path) -eq $Desired }
Set-Content -Path "desired.txt" -Value "ready"
Test-DesiredContent -Path "desired.txt" -Desired "ready"

Set the result when it is wrong

The Set function writes the desired value. The file then holds the right content.

function Set-DesiredContent { param([string]$Path, [string]$Desired) Set-Content -Path $Path -Value $Desired }
Set-Content -Path "desired.txt" -Value "old"
Set-DesiredContent -Path "desired.txt" -Desired "ready"
Get-Content -Path "desired.txt"

Check, fix, check again

Run Test first, and Set only when Test says False. A final Test then returns True.

function Test-DesiredContent { param([string]$Path, [string]$Desired) (Get-Content -Path $Path) -eq $Desired }
function Set-DesiredContent { param([string]$Path, [string]$Desired) Set-Content -Path $Path -Value $Desired }
Set-Content -Path "desired.txt" -Value "old"
if (-not (Test-DesiredContent -Path "desired.txt" -Desired "ready")) { Set-DesiredContent -Path "desired.txt" -Desired "ready" }
Get-Content -Path "desired.txt"
Test-DesiredContent -Path "desired.txt" -Desired "ready"

Example

$desired = "ready"
function Test-DesiredContent { param([string]$Path, [string]$Desired) (Get-Content -Path $Path) -eq $Desired }
function Set-DesiredContent { param([string]$Path, [string]$Desired) Set-Content -Path $Path -Value $Desired }
Set-Content -Path "desired.txt" -Value "old"
if (-not (Test-DesiredContent -Path "desired.txt" -Desired $desired)) { Set-DesiredContent -Path "desired.txt" -Desired $desired }
Get-Content -Path "desired.txt"
Test-DesiredContent -Path "desired.txt" -Desired $desired

Key points

  • Test function: a function that returns True when the result already matches, and False when it does not.
  • Set function: a function that writes the desired result.
  • Pattern: a fixed pair of steps that you reuse for each result you manage.
  • Check first: the Test function runs before the Set function, so work happens only when it is needed.

In this example, the script stores the desired value, defines the Test and Set functions, writes a wrong value, fixes it only because Test says False, and then confirms the file matches.

Note

These are plain PowerShell functions, not the DSC engine.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

The file already holds the desired value. What does the Test function return?