PowerShell automation for Windows Server admins

Checking one server by hand is ordinary admin work, but doing the same check on 200 servers every morning is a job for PowerShell automation. You run the commands remotely, wrap them in a script that copes with errors and schedule it, so the report is already waiting when you get in.

You’ll run commands on all your servers at once, write a reusable server report script with parameters and error handling, schedule the GPO backup from Lesson 20 and use DSC to keep a folder in place. At the end you’ll fix the two problems that catch out every new script writer.

TimeYou needBy the end you can
About 90 minutesDC01, DC02 and SRV01; PowerShell basics from Lesson 7Use Invoke-Command and sessions, write advanced scripts with parameters and try/catch, schedule tasks, use DSC, and solve the double-hop and silent-error problems

What it is, in one line

PowerShell automation means using scripts, remoting and scheduling so PowerShell does repeated admin work across many servers without you typing each command.

In Simple Words

The teacher with a megaphone

A teacher who wants every class to line up can walk to each room and say it 20 times, or she can use the school’s speaker system and say it once, so every room hears the same thing at the same moment. Invoke-Command is that speaker system: one command, every server. A script is the written announcement that anyone can read out the same way, and a scheduled task is the bell that rings at 9:00 every day without anyone pressing it. A good announcement also says what to do if a room is empty, the same way a good script handles a server that doesn’t answer.

Engineer's View

Remoting, scripts, errors, scheduling, DSC

Remoting: PowerShell remoting runs over WinRM (HTTP 5985, HTTPS 5986), is on by default on Windows Server and authenticates with Kerberos in a domain. Invoke-Command -ComputerName a,b,c runs a script block on many computers in parallel (32 at a time by default) and returns objects tagged with PSComputerName, while New-PSSession keeps connections open so you can reuse them.

Scripts: adding [CmdletBinding()] and a param() block makes a script behave like a cmdlet, with typed parameters, -Verbose, and -WhatIf if you use SupportsShouldProcess. Have it output objects rather than text, so the results can be sorted, filtered and exported.

Errors: most cmdlet errors are non-terminating, which means they print red text and carry on, and try/catch never sees them. Add -ErrorAction Stop (or set $ErrorActionPreference) to make them catchable.

Scheduling and DSC: scheduled tasks should run scripts as SYSTEM, a gMSA or a service account, and never as a person. Desired State Configuration describes how a server ought to look and can check for drift or correct it. Then there’s the double hop: a remote session can’t use your credentials to reach a third computer unless delegation has been set up.

How it works, step by step

Here’s how one Invoke-Command reaches three servers and comes back as a single table:

PowerShell automation: Invoke-Command fans out to three servers and merges the results

Each server runs the script block itself and sends objects back, and your console merges them and adds PSComputerName so you can tell which result came from where. If a server is down you get an error for that one name, and the rest still return.

Here’s what you’ll automate in this lab:

PowerShell automation built in the lab: remoting, report script, scheduled backup and DSC
  1. Remote commands on DC01, DC02 and SRV01 at once.
  2. Get-ServerReport.ps1: build, uptime, disk, pending reboot and evaluation days, with error handling.
  3. Scheduled GPO backup on DC01 every night.
  4. DSC: make sure C:\Scripts exists on SRV01.

Hands-on Lab: PowerShell automation across the lab servers

Before you run any command, double-check it

Read every command twice before you press Enter. Check the target: the system or account, the IDs, the names and the sizes. These commands are for learning and were tested in our lab, not on your system. At work, run the read-only list commands first, follow your change process, make sure a backup exists, and ask a second person to check anything that changes or deletes data. You run them at your own risk.

Start DC01, DC02 and SRV01, then sign in to DC01 as SAATLAB\adm.rahul (or Administrator) and work in PowerShell as administrator.

1Run one command on every server

On DC01, run this:

$servers = 'DC01','DC02','SRV01'
Test-WSMan SRV01 | Select-Object ProductVersion
Invoke-Command -ComputerName $servers -ScriptBlock {
    Get-CimInstance Win32_OperatingSystem | Select-Object Caption, LastBootUpTime
} | Select-Object PSComputerName, Caption, LastBootUpTime

You should see something like this:

ProductVersion
--------------
OS: 0.0.0 SP: 0.0 Stack: 3.0

PSComputerName Caption                                             LastBootUpTime
-------------- -------                                             --------------
DC01           Microsoft Windows Server 2025 Datacenter Evaluation 19/10/2026 14:02:11
SRV01          Microsoft Windows Server 2025 Datacenter Evaluation 19/10/2026 16:41:37
DC02           Microsoft Windows Server 2025 Datacenter Evaluation 19/10/2026 14:05:52

Because the servers run in parallel, the results come back in whatever order they answer. Test-WSMan answering tells you WinRM is listening on SRV01.

✅ Checkpoint: All three servers return their OS and last boot time in one table.

2Reuse connections with sessions

On DC01:

$s = New-PSSession -ComputerName $servers
Invoke-Command -Session $s -ScriptBlock { Get-Service W32Time, Netlogon -ErrorAction SilentlyContinue | Select-Object Name, Status } |
    Sort-Object PSComputerName | Format-Table PSComputerName, Name, Status -AutoSize
Remove-PSSession $s

You should see something like this:

PSComputerName Name     Status
-------------- ----     ------
DC01           Netlogon Running
DC01           W32Time  Running
DC02           Netlogon Running
DC02           W32Time  Running
SRV01          Netlogon Running
SRV01          W32Time  Running

When you send a lot of commands, a session saves you the connection setup each time and keeps your variables between calls. Remove your sessions when you’ve finished.

✅ Checkpoint: Netlogon and W32Time are Running on all three servers.

3Write Get-ServerReport.ps1

On DC01, create C:\Scripts\Get-ServerReport.ps1 with this content (in Notepad or VS Code):

[CmdletBinding()]
param(
    [Parameter(Mandatory)][string[]]$ComputerName,
    [string]$OutFile = "C:\Scripts\ServerReport-$(Get-Date -Format yyyyMMdd).csv"
)
$results = foreach ($c in $ComputerName) {
    try {
        Invoke-Command -ComputerName $c -ErrorAction Stop -ScriptBlock {
            $os  = Get-CimInstance Win32_OperatingSystem
            $cv  = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
            $disk = Get-CimInstance Win32_LogicalDisk -Filter "DeviceID='C:'"
            $lic = Get-CimInstance SoftwareLicensingProduct -Filter "Name LIKE 'Windows%' AND PartialProductKey IS NOT NULL"
            [pscustomobject]@{
                Build      = "$($cv.CurrentBuild).$($cv.UBR)"
                UptimeDays = [math]::Round(((Get-Date) - $os.LastBootUpTime).TotalDays, 1)
                CFreePct   = [math]::Round($disk.FreeSpace / $disk.Size * 100)
                Reboot     = Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending'
                EvalDays   = [math]::Round($lic.GracePeriodRemaining / 1440)
                Status     = 'OK'
            }
        } | Select-Object @{n='Computer';e={$_.PSComputerName}}, Build, UptimeDays, CFreePct, Reboot, EvalDays, Status
    }
    catch {
        Write-Warning "$c : $($_.Exception.Message)"
        [pscustomobject]@{ Computer = $c; Build = $null; UptimeDays = $null; CFreePct = $null; Reboot = $null; EvalDays = $null; Status = 'Unreachable' }
    }
}
$results | Export-Csv $OutFile -NoTypeInformation
$results

Every server sits inside its own try/catch with -ErrorAction Stop, so a dead server turns into a row saying “Unreachable” and the rest of the report carries on. The script pulls together checks from earlier lessons: the build from Lesson 24, the evaluation days from Lesson 4 and pending reboot from Lesson 24.

Run it, and include a server that doesn’t exist:

New-Item -ItemType Directory C:\Scripts -Force | Out-Null
C:\Scripts\Get-ServerReport.ps1 -ComputerName DC01, DC02, SRV01, SRV99 | Format-Table -AutoSize

You should see something like this:

WARNING: SRV99 : WinRM cannot process the request. ... The specified computer name is not valid or ...

Computer Build      UptimeDays CFreePct Reboot EvalDays Status
-------- -----      ---------- -------- ------ -------- ------
DC01     26100.NNNN        0.3       71 False       172 OK
DC02     26100.NNNN        0.3       78 False       173 OK
SRV01    26100.NNNN        0.1       64 False       174 OK
SRV99                                                   Unreachable

✅ Checkpoint: The report lists the three real servers with Status OK, SRV99 as Unreachable, and a CSV in C:\Scripts.

PowerShell automation lab: server report with an unreachable server handled
Every server is in the report, and SRV99 shows up as an “Unreachable” row rather than stopping the script.

4Schedule the nightly GPO backup

On DC01, register a task that runs as SYSTEM every night at 01:30:

$action  = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -Command "Backup-GPO -All -Path C:\GPOBackups | Out-Null"'
$trigger = New-ScheduledTaskTrigger -Daily -At 01:30
Register-ScheduledTask -TaskName 'Nightly GPO backup' -Action $action -Trigger $trigger -User 'SYSTEM' -RunLevel Highest | Out-Null
Start-ScheduledTask -TaskName 'Nightly GPO backup'
Start-Sleep -Seconds 20
Get-ScheduledTaskInfo -TaskName 'Nightly GPO backup' | Select-Object LastRunTime, LastTaskResult, NextRunTime

You should see something like this:

LastRunTime         LastTaskResult NextRunTime
-----------         -------------- -----------
19/10/2026 21:04:10              0 20/10/2026 01:30:00

LastTaskResult 0 means success. On a DC, SYSTEM acts as the DC’s computer account, which can read every GPO. If a task has to reach other servers, run it as a gMSA that’s allowed on the task’s server and has only the rights the task needs, and never under a person’s account.

✅ Checkpoint: The task ran once with result 0 and is scheduled for 01:30.

5Keep a folder in place with DSC

On SRV01, write a tiny configuration and apply it:

Configuration ServerBasics {
    Node 'localhost' {
        File ScriptsFolder {
            DestinationPath = 'C:\Scripts'
            Type            = 'Directory'
            Ensure          = 'Present'
        }
    }
}
ServerBasics -OutputPath C:\DSC\ServerBasics | Out-Null
Start-DscConfiguration -Path C:\DSC\ServerBasics -Wait -Force
Test-DscConfiguration

You should see this:

True

Now delete C:\Scripts on SRV01 and run Test-DscConfiguration again, and this time it says False; Start-DscConfiguration -UseExisting -Wait puts the folder back. Real configurations describe features, services, registry values and files, and you apply them the same way.

✅ Checkpoint: Test-DscConfiguration returns True, then False after deleting the folder, then True after re-applying.

Break It, Then Fix It

Every script writer runs into these two in their first month: errors that try/catch can’t see, and the “double hop”.

1Break it: a catch block that never runs

On DC01, run this:

try {
    Get-CimInstance Win32_OperatingSystem -ComputerName SRV99
    'Got here, so I think it worked'
}
catch {
    'Caught the error'
}

You’ll see something like this:

Get-CimInstance : WinRM cannot process the request. The following error with errorcode 0x80090311 occurred while
using Kerberos authentication: ...
    + CategoryInfo          : AuthenticationError: (root\cimv2:Win32_OperatingSystem:String) [Get-CimInstance], CimException
    + FullyQualifiedErrorId : HRESULT 0x8033810c,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand
    + PSComputerName        : SRV99

Got here, so I think it worked

The error was printed, but because it was non-terminating the script carried on and reported that it worked. In a scheduled task nobody sees the red text, only the false “success”, and that’s how reports end up quietly missing servers.

Fix it: make the error terminating so catch can handle it:

try {
    Get-CimInstance Win32_OperatingSystem -ComputerName SRV99 -ErrorAction Stop
    'Got here, so I think it worked'
}
catch {
    "Caught: $($_.Exception.Message.Split('.')[0])"
}

You should see something like this:

Caught: WinRM cannot process the request

✅ Checkpoint: Without -ErrorAction Stop the script claimed success; with it, the catch block ran.

2Break it: the double hop

On DC01, ask SRV01 to read a share on DC01:

Invoke-Command -ComputerName SRV01 -ScriptBlock { Get-ChildItem \\DC01\NETLOGON }

You’ll get an error like this:

Access is denied
    + CategoryInfo          : PermissionDenied: (\\DC01\NETLOGON:String) [Get-ChildItem], UnauthorizedAccessException
    + FullyQualifiedErrorId : ItemExistingCheckError,Microsoft.PowerShell.Commands.GetChildItemCommand
    + PSComputerName        : SRV01

You’re an admin and everyone can read the share, yet you’re denied. Your Kerberos ticket got you from DC01 to SRV01 (hop one), but SRV01 has no credentials of yours to show DC01 (hop two). Windows does this deliberately, so that a compromised server can’t reuse your identity.

Fix it: pass a credential explicitly for the second hop:

$cred = Get-Credential SAATLAB\adm.rahul
Invoke-Command -ComputerName SRV01 -ScriptBlock {
    New-PSDrive -Name N -PSProvider FileSystem -Root \\DC01\NETLOGON -Credential $using:cred | Out-Null
    Get-ChildItem N:\ | Select-Object Name
    Remove-PSDrive N
}

The credential travels encrypted inside the session and is used only for that drive. For a permanent answer, set up resource-based constrained delegation on the target or run the work directly on the computer that holds the data, and don’t switch on CredSSP everywhere to “fix” it.

✅ Checkpoint: The direct second hop was denied, and the explicit credential worked.

PowerShell automation lab: Access is denied from the double-hop problem
Hop one works, but hop two from SRV01 to DC01 has no credentials, so access is denied.

This happened at work

The scheduled task that belonged to Ravi

Ravi, a senior admin, had written a good set of scripts: nightly log cleanup on the web servers, a morning disk report and a weekly certificate check. He’d scheduled all of them under his own account because that was the quickest way. Then Ravi moved to another company, and on his last day his account was disabled, as it should be. That same night every one of his tasks started failing with LastTaskResult 0x8007052F (logon failure), and nobody was watching task results. Five weeks later the log drives on the web servers filled up, and IIS stopped writing logs and then stopped serving pages. While digging into that, the team found the certificate check hadn’t run either, which explained an expired certificate they’d been chasing.

The fix: every task moved to a gMSA with the minimum rights it needed, the scripts went into source control, and a daily check now flags any task whose LastTaskResult isn’t 0.

The lesson: don’t let automation depend on one person’s account. Use managed accounts, and keep an eye on the results of the automation itself.

Common mistakes and troubleshooting

Mistake or symptomWhat happensWhat to do instead
try/catch without -ErrorAction StopErrors are printed and ignored; false success-ErrorAction Stop on commands that must succeed
Scheduled tasks under a person’s accountTasks fail when the person leaves or changes passwordSYSTEM or a gMSA with minimal rights
“Access is denied” on a second computer from a remote sessionDouble hop: no credentials for hop twoExplicit -Credential, RBCD, or run the work locally
Turning on CredSSP everywhereCredentials exposed on remote serversUse RBCD or explicit credentials only where needed
Scripts that output formatted textResults can’t be sorted or exportedOutput objects; format only at the end
No -WhatIf on scripts that change thingsMistakes happen at full scaleSupportsShouldProcess and test with -WhatIf
Not watching task resultsSilent failures for weeksReport on LastTaskResult and script logs daily
Hard-coded server listsNew servers are missedRead targets from AD (Get-ADComputer) or a CMDB
Scripts only on someone’s desktopLost work and no historySource control and a shared, protected scripts location

Interview questions

Click a question to open it. Each one is phrased the way an interviewer would ask it, and underneath you’ll find why they ask it and one way you could answer in your own words.

Fresher level

1. Your manager asks you to check a service on ten servers at once. How would you run one command on all of them?

Why they ask this: They’re checking you know PowerShell remoting basics and don’t log in to each server one by one.

How you might answer: I’d use Invoke-Command -ComputerName with the list of server names and a script block. Each result comes back tagged with PSComputerName, so I can see which answer came from which server.

2. The firewall team asks which ports PowerShell remoting needs. What would you tell them?

Why they ask this: They want to know you understand WinRM and how remoting is protected in a domain.

How you might answer: It uses WinRM, TCP 5985 for HTTP and 5986 for HTTPS. In a domain the traffic is still encrypted by Kerberos even on 5985.

3. You wrote a clean-up script and want it to run every night. How would you schedule it?

Why they ask this: They want to see you’ve done this before and know which account the task should run as.

How you might answer: I’d use Task Scheduler or Register-ScheduledTask with an action that runs powershell.exe -File and the script path, a trigger for the time, and a principal like SYSTEM or a gMSA so it doesn’t depend on my own account.

2–5 years experience

4. Your script has a try/catch, but an error still slips through without going to the catch block. Why does that happen?

Why they ask this: They’re checking you understand terminating and non-terminating errors, which catch out a lot of script writers.

How you might answer: Most cmdlet errors are non-terminating, and try/catch only sees terminating ones. So I’d add -ErrorAction Stop to the command, or put $ErrorActionPreference = 'Stop' at the top of the script.

5. In a remote session you try to copy a file from a third server and get access denied. What’s going on, and how would you fix it?

Why they ask this: They want to see that you recognise the double-hop problem and know the safe ways around it.

How you might answer: That’s the double-hop problem: from a remote session my credentials can’t be passed on to a third computer. I’d fix it with explicit credentials, resource-based constrained delegation or a JEA run-as account, or I’d run the task directly on the target.

6. Your team shares a lot of scripts. How would you make one of them behave like a proper cmdlet?

Why they ask this: They want to know whether you write advanced functions that other people can use safely.

How you might answer: I’d add [CmdletBinding()] and a param block with types and validation, and with SupportsShouldProcess it picks up -WhatIf and -Confirm. I’d use Write-Verbose for the extra detail and have it output objects rather than formatted text.

Senior level

7. You’re asked to build a daily health report for 300 servers. How would you design it so it’s reliable?

Why they ask this: They want to see you think about scale, failures and upkeep, not only a script that works once.

How you might answer: I’d pull the server list from AD and use parallel remoting with throttling, with a try/catch per server so one failure doesn’t stop the rest, and send the results to CSV or HTML and a database. It would run as a gMSA from a management server, alert on failures, and the script would live in source control with tests.

8. When would you use DSC instead of normal scripts?

Why they ask this: They want to see that you understand configuration management and pick the right approach for the job.

How you might answer: DSC is for when I want to declare a desired state for many servers and keep them there, because it detects and corrects drift and the configuration can be reviewed as code. For one-off jobs or step-by-step tasks, a normal script is the better fit.

9. The helpdesk needs to restart a few services on servers, but you don’t want to give them admin rights. How would you do it?

Why they ask this: They’re checking you know JEA and can apply least privilege in practice.

How you might answer: I’d set up Just Enough Administration, with a constrained endpoint whose role capabilities expose only the cmdlets and parameters the helpdesk needs. It runs as a virtual account or a gMSA, and transcripts record everything they do.

Quick quiz

Q1. What does Invoke-Command add to each result?

  1. A timestamp
  2. PSComputerName
  3. An error code
Show answer

B — So you know which server answered.

Q2. Why didn’t the first catch block run?

  1. Wrong syntax
  2. The error was non-terminating
  3. SRV99 was up
Show answer

B — Add -ErrorAction Stop.

Q3. What causes the double-hop problem?

  1. A firewall
  2. The remote session has no credentials for a third computer
  3. Slow DNS
Show answer

B — Use explicit credentials or RBCD.

Q4. What does LastTaskResult 0 mean?

  1. Never run
  2. Success
  3. Access denied
Show answer

B — Anything else needs checking.

Q5. In the work story, why did the tasks fail?

  1. A bad patch
  2. They ran under an account that was disabled
  3. The disk was full
Show answer

B — Use gMSAs for automation.

Quick recap

  • PowerShell automation runs work across many servers with remoting, scripts and schedules.
  • Invoke-Command runs in parallel, and sessions let you reuse connections.
  • Advanced scripts use [CmdletBinding()], typed parameters and object output.
  • try/catch needs -ErrorAction Stop to see most errors.
  • Schedule tasks as SYSTEM or a gMSA (never as a person) and keep an eye on LastTaskResult.
  • Getting past the double hop takes explicit credentials or delegation.

Next lesson

Lesson 28: Hyper-V basics → Next you’ll turn on Hyper-V on your own laptop (VirtualBox can’t reliably run it as a nested guest), create virtual switches and a VM, work with checkpoints and see why a Hyper-V host needs planning of its own.

Further reading: PowerShell automation

Want to go deeper into PowerShell automation? Microsoft’s second hop guide compares every double-hop solution, and the about_Try_Catch_Finally help explains error handling. You can also see the full plan for this course on the Windows Server Administration course page.

Scroll to Top

This website uses cookies

We use a few cookies to keep this site working. If you allow it, we also use Google Analytics to count visits so we can improve our lessons. You can accept all, deny the optional ones, or choose what to allow.