Logging on to servers one by one over RDP every morning to check disk space, listing inactive accounts by hand every month, remembering the log folder when the volume fills up: all of these are tasks prone to being forgotten, and one day they will be. PowerShell turns these repetitions into scripts. Below are working examples for the tasks systems teams most often do by hand, including running remotely on multiple servers, running as a scheduled task, error handling and keeping scripts organized within the organization.
Which tasks are suitable for automation
Scripting every task doesn’t make sense. Good candidates have common traits:
- They repeat: The same steps daily, weekly, or for every new user/server.
- They follow rules: They have a clear criterion such as “accounts that haven’t signed in for 90 days”; they don’t require human interpretation.
- The cost of errors is manageable: They fit a structure that reports first and changes after approval.
In practice, this means starting with reporting. A reporting script doesn’t change the environment; if it runs wrong, it produces a wrong report, that’s all. Move on to scripts that make changes (disabling accounts, deleting files) after the reports have given correct results for a few weeks. Read first, then write.
PowerShell Remoting and Invoke-Command
The foundation of multi-server management is PowerShell Remoting running over WinRM. It is enabled by default on Windows Server; if it’s off, enable it with Enable-PSRemoting -Force. Within a domain, authentication is done with Kerberos; even though traffic is over HTTP (5985/TCP), it is encrypted by the Kerberos session. Servers outside the domain need an HTTPS listener (5986/TCP) and a certificate. If a connection can’t be made, the first order of checks is: is the WinRM service running on the target, is the firewall port open, does the name resolve to the right IP in DNS? Test-WSMan servername shows in a single command whether the WinRM endpoint can be reached.
Invoke-Command runs the script block in parallel on all servers in the list (the default concurrency limit is 32, changed with -ThrottleLimit) and adds a PSComputerName property to each result showing the source server:
$servers = Get-Content "C:\Scripts\servers.txt"
Invoke-Command -ComputerName $servers -ScriptBlock {
(Get-CimInstance Win32_OperatingSystem).LastBootUpTime
} | Select-Object PSComputerName, @{n='LastBoot';e={$_}}
If you will send many commands to the same servers in a row, instead of creating a new connection each time, open the sessions once with New-PSSession and reuse them with Invoke-Command -Session $s; the difference is noticeable. The most common trap is the “double hop” problem: accessing a third resource from inside a remote session, for example a file share, fails with “Access denied” because credentials aren’t delegated by default. The command works locally but not remotely, and the team spends hours looking for permissions. The simplest solution is to return the result to the local machine and write the file locally. If access to the resource from the remote session is really needed, prefer resource-based Kerberos constrained delegation. Use CredSSP, which leaves credentials on the remote server, only after weighing its risk.
Example: disk and service status report
The script below collects free space on fixed disks, and services that should start automatically but aren’t running, from all servers:
$servers = Get-Content "C:\Scripts\servers.txt"
$date = Get-Date -Format "yyyy-MM-dd"
$disk = Invoke-Command -ComputerName $servers -ScriptBlock {
Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" |
Select-Object DeviceID,
@{n='SizeGB';e={[math]::Round($_.Size/1GB,1)}},
@{n='FreeGB';e={[math]::Round($_.FreeSpace/1GB,1)}},
@{n='FreePct';e={[math]::Round($_.FreeSpace/$_.Size*100,1)}}
} | Select-Object PSComputerName, DeviceID, SizeGB, FreeGB, FreePct
$disk | Where-Object FreePct -lt 15 |
Export-Csv "C:\Reports\disk-$date.csv" -NoTypeInformation -Encoding UTF8
$service = Invoke-Command -ComputerName $servers -ScriptBlock {
Get-CimInstance Win32_Service -Filter "StartMode='Auto' AND State<>'Running'" |
Select-Object Name, DisplayName, State
} | Select-Object PSComputerName, Name, DisplayName, State
$service | Export-Csv "C:\Reports\service-$date.csv" -NoTypeInformation -Encoding UTF8
In the service report, some services naturally appear stopped: such as “Automatic (Delayed Start)” or trigger-start services. If you don’t filter them with an exclusion list, the report produces the same noise every day and becomes unread by the second week. The continuous monitoring side is described in the server monitoring metrics and thresholds article. A script report doesn’t replace the monitoring system; it’s for seeing the inventory gaps that monitoring doesn’t catch.
Example: AD account reports
Unused and risky accounts are reported with the ActiveDirectory module (via RSAT or on a domain controller):
Import-Module ActiveDirectory
# Enabled users who haven't signed in for 90 days
Search-ADAccount -AccountInactive -TimeSpan 90.00:00:00 -UsersOnly |
Where-Object Enabled |
Select-Object Name, SamAccountName, LastLogonDate, DistinguishedName |
Export-Csv "C:\Reports\inactive-users.csv" -NoTypeInformation -Encoding UTF8
# Enabled users whose password never expires
Get-ADUser -Filter 'Enabled -eq $true -and PasswordNeverExpires -eq $true' `
-Properties PasswordLastSet, PasswordNeverExpires |
Select-Object Name, SamAccountName, PasswordLastSet
# Computers that haven't connected to the domain for 90 days
Search-ADAccount -AccountInactive -TimeSpan 90.00:00:00 -ComputersOnly |
Where-Object Enabled |
Select-Object Name, LastLogonDate, DistinguishedName
LastLogonDate is derived from the replicated lastLogonTimestamp attribute. This attribute is updated only if the previous value is older than a certain interval (14 days by default, with random variance). So the value can lag the real last sign-in by up to two weeks. That doesn’t matter for a 90-day threshold; but it doesn’t answer the question “did they sign in yesterday?” Before connecting the report to a disabling step, put service and administrator accounts on an exclusion list. Otherwise an application’s service account gets disabled at midnight and the first phone call comes in the morning. Account reports can be run as part of the Active Directory health check process together with the directory’s overall health.
Example: log cleanup
IIS, application or backup agent logs fill the volume over time, and when the volume fills, the service stops. In a script that deletes, always try first with -WhatIf:
$days = 30
Get-ChildItem -Path "D:\Logs\IIS" -Filter *.log -Recurse -File |
Where-Object LastWriteTime -lt (Get-Date).AddDays(-$days) |
Remove-Item -WhatIf # remove -WhatIf after verifying the result
Before deleting, verify that the retention period doesn’t conflict with corporate policy, audit or legal obligations. Some logs aren’t deleted but moved to an archive volume. A deletion script with a mistyped path variable doesn’t leave room for a second try.
Running as scheduled tasks
Scripts are registered as scheduled tasks with the ScheduledTasks module. Running the task under a personal administrator account causes two separate problems: when the password changes, the task silently breaks, and when the person leaves the company, the team that disables the account unknowingly disables the reports too. In a domain, the right choice is a group managed service account (gMSA), whose password AD manages automatically. After the account is created, installed on the server with Install-ADServiceAccount and verified with Test-ADServiceAccount:
$action = New-ScheduledTaskAction -Execute "powershell.exe" `
-Argument '-NoProfile -File "C:\Scripts\DiskReport.ps1"'
$trigger = New-ScheduledTaskTrigger -Daily -At 07:00
$principal = New-ScheduledTaskPrincipal -UserId 'CORP\gmsa-report$' -LogonType Password
Register-ScheduledTask -TaskName "Daily Disk Report" -Action $action `
-Trigger $trigger -Principal $principal
For a gMSA, -LogonType Password is specified but no password is entered; the password comes from AD. The account must have the “Log on as a batch job” right on the server. Without this right, the task is registered but doesn’t run; you see a logon error in the task history. Give the account only the rights the script needs. Read access is enough for an AD report. Domain Admins membership is unnecessary and risky.
Error handling and logging
A script running in a scheduled task doesn’t write its errors to the screen. Nobody sees them. Therefore:
- In PowerShell, most errors are “non-terminating” and aren’t caught by
try/catch. Add-ErrorAction Stopto critical commands or define$ErrorActionPreference = 'Stop'at the start of the script. - Write each run to a timestamped log file.
Start-Transcriptis a quick start; structured logs (date, level, server, message) make searching easier later. - Report unreachable servers separately. Servers that
Invoke-Commandcan’t connect to can be collected with-ErrorVariable; otherwise the report is incomplete but looks “successful.” That is the most dangerous report. - Return a non-zero exit code on failure (
exit 1); the scheduled task history and the monitoring system see it.
$ErrorActionPreference = 'Stop'
$log = "C:\Scripts\Logs\DiskReport-$(Get-Date -Format yyyyMMdd).log"
function Write-Log($Level, $Message) {
"{0:yyyy-MM-dd HH:mm:ss} [{1}] {2}" -f (Get-Date), $Level, $Message |
Add-Content -Path $log -Encoding UTF8
}
try {
Write-Log INFO "Report started"
# ... business logic ...
Write-Log INFO "Report completed"
}
catch {
Write-Log ERROR $_.Exception.Message
exit 1
}
The Send-MailMessage cmdlet, still often seen for sending reports by email, has been marked obsolete by Microsoft. In new scripts, use a mail method your organization supports or drop the report on a share.
Script management and version control
Scripts scattered across server desktops with names like new_final2.ps1 are the biggest operational risk of server management automation. Nobody knows which one is running. For a sustainable setup:
- Keep all scripts in a Git repository; merge changes with review.
- Collect common functions (logging, reading the server list) in a module (
.psm1and.psd1). - Don’t write information such as passwords or API keys into scripts; use gMSA, the Windows credential store or the Microsoft.PowerShell.SecretManagement module.
- State dependencies explicitly with declarations such as
#Requires -Modules ActiveDirectory; run static checks withInvoke-ScriptAnalyzer(PSScriptAnalyzer). - Set the execution policy to
RemoteSigned, orAllSignedif you have a code signing infrastructure. As Microsoft also states, this policy isn’t a security boundary but a safeguard against running scripts unintentionally.
To combine automation with patching and maintenance processes, the server patch management article is a complement, and to verify configurations made with GPO, the Group Policy troubleshooting article. Building PowerShell skills within the team can be planned within IT consulting and training. Official sources: about_Remote and about_Execution_Policies in Microsoft Learn.
Frequently asked questions
What needs to be configured on servers for Invoke-Command?
PowerShell Remoting is enabled by default on domain-joined Windows Server versions. If it’s off, enable it with Enable-PSRemoting -Force; the firewall needs to allow 5985/TCP for WinRM, and 5986/TCP if HTTPS is used.
Why doesn’t try/catch catch some errors?
In PowerShell, many cmdlet errors are non-terminating and don’t fall into the catch block. Adding -ErrorAction Stop to the command or setting $ErrorActionPreference to Stop makes these errors catchable.
Which account should a scheduled task run as?
In a domain, a group managed service account (gMSA); AD changes its password automatically. Give the account only the least privilege the script needs.
Does the execution policy make scripts secure?
No. The execution policy isn’t a security boundary; it only makes it harder to run scripts unintentionally. For security, keep scripts in version control, sign them and run them with the least privilege.