The DRY Principle: How to Write Better PowerShell Code

$TextFile1 = 'textfile3.txt'
$TextFile2 = 'textfile2.txt'
$TextFile3 = 'textfile1.txt'
## Get the content of all the text files
$Content1 = Get-Content $TextFile1
$Content2 = Get-Content $TextFile2
$Content3 = Get-Content $TextFile3
## Merge all text file content together to create a single text file $AppendedContent = $Content1 + $Content2 + $Content3 $AppendedContent | Add-Content 'C:\mergedtextcontent.txt'

It’s Not Reusable

It’s Not Extensible

  • Don’t write a script that’s a fully-developed solution.
  • Write scripts to do one thing and one thing only.
  • Allow yourself or someone else to build upon it in an easy-to-understand manner.
$TextFile1 = 'textfile3.txt'
$TextFile2 = 'textfile2.txt'
## Test to ensure the file is there
if (!(Test-Path $TextFile1)) {
Write-Output "The $TextFile1 file isn't there"
} else {
## Get the content of all the text files
$Content1 = Get-Content $TextFile1
}
if (!(Test-Path $TextFile2)) {
Write-Output "The $TextFile2 file isn't there"
} else {
## Get the content of all the text files
$Content2 = Get-Content $TextFile2
}

It’s Not Readable

Occam’s Razor — The best solution is always the simplest

Notice patterns in the code and simplify them

$MyTextFiles = Get-ChildItem 'C:\MyTextFiles'
$MyTextFilesContent = Get-ChildItem 'C:\MyTextFiles' | Get-Content

Combine like elements in arrays or hashtables

@('C:\MyTextFiles\textfile3.txt','C:\SomeOtherFolder\textfile2.txt','C:\Windows\textfile1.txt')
@('C:\MyTextFiles\textfile3.txt','C:\SomeOtherFolder\textfile2.txt','C:\Windows\textfile1.txt') | Get-Content

Use functions

function Get-MyContent ($FilePath) {
if (!(Test-Path $FilePath)) {
$false
} else {
Get-Content $FilePath
}
}
$TextFiles = @('C:\MyTextFiles\textfile3.txt','C:\SomeOtherFolder\textfile2.txt','C:\Windows\textfile1.txt')
$CombinedOutput = ''
foreach ($TextFile in $TextFiles) {
$Content = Get-MyContent -FilePath $TextFile
if ($Content) {
$CombinedContent += $Content
}
}

Summary

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adam Bertram

Adam Bertram

A 20-year veteran of IT, crypto geek, content creator, consultant and overall problem solver.