IT Manager candidate based in Riyadh. 12+ years in IT operations and infrastructure.
+966 55 973 2392
https://www.islamfathi.com
Riyadh, Saudi Arabia
Most scripts start as a quick fix and end up scheduled on a server. WhatIf support, error handling, logging and keeping secrets out.
Most scripts start as a quick fix and end up scheduled on a server. A few habits make the difference between a script you trust and one you are afraid to run.
Make the script show what it would do before it does it. PowerShell has this built in through SupportsShouldProcess.
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)][string]$SearchBase,
[int]$Days = 90
)
$cutoff = (Get-Date).AddDays(-$Days)
Get-ADComputer -SearchBase $SearchBase -Filter {LastLogonDate -lt $cutoff} -Properties LastLogonDate |
ForEach-Object {
if ($PSCmdlet.ShouldProcess($_.Name, 'Disable computer account')) {
Disable-ADAccount -Identity $_
}
}
Run it with -WhatIf first and read the list.
By default many errors do not stop a script. Use -ErrorAction Stop on the commands that matter and wrap them in try and catch, so a failure is handled instead of ignored.
Write a log file with the date in the name, or use Start-Transcript. When a scheduled script misbehaves at night, the log is all you have.
Never put passwords in a script. Use a managed service account, the Windows credential store or a secrets vault.
Test on one OU or a handful of objects, then widen the scope. Put a short comment at the top that says what the script does and who owns it.
Your email address will not be published. Required fields are marked *