IT Manager candidate based in Riyadh. 12+ years in IT operations and infrastructure.

Phone

+966 55 973 2392

Website

https://www.islamfathi.com

Address

Riyadh, Saudi Arabia

Social Links

Coding Challenges

Writing a PowerShell script people can trust

Most scripts start as a quick fix and end up scheduled on a server. WhatIf support, error handling, logging and keeping secrets out.

Writing a PowerShell script people can trust

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.

Add -WhatIf support

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.

Stop on errors you care about

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.

Log what happened

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.

Keep secrets out of the file

Never put passwords in a script. Use a managed service account, the Windows credential store or a secrets vault.

Try it small

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.

2 min read
Jun 23, 2026
By Islam Fathy
Share

Leave a comment

Your email address will not be published. Required fields are marked *

Your experience on this site will be improved by allowing cookies. We use cookies to enhance performance and improve your browsing experience. Cookie Policy