What if you could write a command once and use it everywhere without copying it again?
Why Function definition in PowerShell? - Purpose & Use Cases
Imagine you need to repeat the same set of commands multiple times in your PowerShell script, like checking disk space or formatting output. Without functions, you have to copy and paste the same lines everywhere.
Copying and pasting code is slow and risky. If you find a mistake, you must fix it in every place manually. This wastes time and can cause errors if you miss one spot.
Functions let you write a block of code once and give it a name. Then you just call that name whenever you need it. This keeps your script clean, easy to read, and simple to update.
Write-Host "Checking disk space..." Get-PSDrive C | Select-Object Used, Free Write-Host "Checking disk space..." Get-PSDrive D | Select-Object Used, Free
function Check-DiskSpace($drive) {
Write-Host "Checking disk space on $drive..."
Get-PSDrive -Name $drive | Select-Object Used, Free
}
Check-DiskSpace C
Check-DiskSpace DFunctions let you build scripts that are easier to manage, update, and reuse, saving you time and reducing mistakes.
System administrators often write functions to automate daily tasks like user account creation or log cleanup, so they don't have to repeat the same commands every day.
Functions group repeated code into one place.
They make scripts easier to read and fix.
Calling a function is faster than rewriting code.