System administrators and IT students often face the tedious task of checking the status of multiple Windows services across different servers or local machines. While standard commands like Get-Service work, they output raw data that can be difficult to parse quickly during an incident response or routine maintenance window. By leveraging PowerShell’s object-oriented capabilities, you can create a custom function that not only queries service states but formats the output for immediate readability. This guide walks you through building a robust function using Get-Service, Format-Table, and conditional logic to handle various scenarios safely and effectively.
Understanding the Prerequisites and Environment
Before writing your first line of code, it is essential to understand the environment where this function will run. The primary tool required is Windows PowerShell (version 5.1 or newer) or PowerShell Core. While you can execute these scripts on standard Windows installations, many modern IT environments utilize WSL (Windows Subsystem for Linux) or remote server management via PSSession.
For this tutorial, we will assume a standard Windows Server or Windows 10/11 environment. The function relies on the built-in Microsoft.Win32.ServiceController cmdlets, which are available by default without needing to install third-party modules like PSWindowsUpdate or specific server roles.
Key Concepts:
* Cmdlets: Commands that perform tasks (e.g., Get-Service).
* Script Blocks: The logic enclosed in curly braces {} where your custom code resides.
* Parameters: Inputs defined at the beginning of a function, allowing flexibility without editing the code itself.
Step-by-Step Guide to Building the Custom Function
We will create a function named Get-ServiceStatusReport. This function accepts one or more service names as arguments and returns a formatted table displaying the Service Name, Display Name, Status, Start Type, and Path.
Defining the Function Structure
Open your PowerShell ISE or an editor like VS Code. Paste the following code into a new file or the console:
function Get-ServiceStatusReport {
<#
.SYNOPSIS
Queries and displays running service status in a formatted table.
.DESCRIPTION
Accepts one or more service names, checks their current state,
and outputs a clean report including start type and path.
.PARAMETER ServiceName
The name of the Windows service to query (e.g., 'Spooler').
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
[string[]]$ServiceName
)
Process {
foreach ($svc in $ServiceName) {
try {
# Retrieve the service object
$service = Get-Service -Name $svc -ErrorAction Stop
# Determine status color for readability (optional logic)
$statusColor = if ($service.Status -eq 'Running') { '[OK]' } else { '[WARN]' }
# Output the formatted data
[PSCustomObject]@{
ServiceName = $svc
DisplayName = $service.DisplayName
Status = $service.Status
StartType = $service.StartType
Path = $service.ServicePath
StatusColor = $statusColor
} | Format-Table -AutoSize
}
catch {
# Handle services that do not exist
[PSCustomObject]@{
ServiceName = $svc
DisplayName = 'N/A'
Status = 'NotFound'
StartType = 'N/A'
Path = 'N/A'
StatusColor = '[ERR]'
} | Format-Table -AutoSize
}
}
}
}
Explaining the Code Logic
- Function Definition: The
functionkeyword declares a new command. TheParamblock defines inputs. Here, we require at least one service name (ServiceName). - Error Handling: The
try/catchblock is critical for production environments. If you query a non-existent service (e.g.,Get-Service -Name 'FakeService'), the default behavior throws an error and stops execution.-ErrorAction Stopensures we catch this gracefully, allowing the function to report “NotFound” instead of crashing. - Object Creation:
[PSCustomObject]creates a dynamic object with specific properties. This allows us to add custom columns likeStatusColorwhich isn’t part of the native service object but improves visual scanning. - Formatting:
Format-Table -AutoSizeadjusts column widths automatically, preventing text from spilling over in the console.
Expected Results and Verification
Once you save this script (e.g., as Get-ServiceStatusReport.ps1) and run it, you will see a clean table.
Illustrative Output:
+------------------+----------------------+----------+------------+-------------------+-----------+
| ServiceName | DisplayName | Status | StartType | Path | StatusColor|
+------------------+----------------------+----------+------------+-------------------+-----------+
| Spooler | Print Spooler | Running | Automatic | C:\Windows\System... [OK]
| WlanSvc | Wireless LAN | Running | Automatic | ... [OK]
| FakeService | N/A | NotFound | N/A | N/A [ERR] |
+------------------+----------------------+----------+------------+-------------------+-----------+
Verification Steps:
1. Manual Check: Open the native services.msc console or run Get-Service Spooler. Compare the status and path with your function’s output. They must match exactly.
2. Pipe Testing: In PowerShell, you can pipe a list of services directly into the function:
powershell
"Spooler", "WlanSvc", "Bios" | Get-ServiceStatusReport
This demonstrates the ValueFromPipeline = $true parameter, allowing automation scripts to pass data streams efficiently.
Common Errors and Troubleshooting
When working with service queries, several issues frequently arise in real-world scenarios:
- Error: “Cannot find an object with name…”: This usually means the service name is misspelled or the service was renamed by a patch update. Always verify the exact spelling using
Get-Service *first. - Permission Denied: If running from a user account without admin privileges, you may not be able to query certain services. Ensure your script runs with elevated rights (
Run as Administrator) if accessing system-level services. - WSL Compatibility: If executing this on WSL (Linux terminal), standard Windows service cmdlets will fail because the underlying OS architecture differs. You must run this code within a Windows PowerShell console, not the Bash terminal inside WSL.
Industry Application and Student Practice Task
Student Practice Task:
Create a script that monitors three critical services: W3SVC (IIS), Spooler, and WinDefend (Antivirus). Save these names in an array variable, pipe them into your new function, and export the result to a CSV file named ServiceCheck_$(Get-Date -Format yyyy-MM-dd).csv. This simulates a nightly health check job.
Industry Application:
In a corporate environment, this function can be integrated into a scheduled task (Task Scheduler) to run every morning at 8:00 AM. The output CSV can be emailed to the IT Operations team or posted to a monitoring dashboard. By adding logic to check if Status equals Stopped, you could automatically trigger an alert ticket via ServiceNow or Jira if critical infrastructure services are down.
Conclusion
Creating custom PowerShell functions transforms raw system data into actionable intelligence. By wrapping standard cmdlets like Get-Service in a reusable function with error handling and formatting, you save time during troubleshooting and reduce the risk of human error in reading console output. Always remember to test these scripts in a safe lab environment before deploying them to production servers, and ensure your team understands that terms, availability, and permissions depend on the specific OS version and jurisdictional security policies.
Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.

