---
title: PowerShell scripts for monitoring and automation with Nodinite Windows Server Agent
description: Monitor, automate, and empower users with custom PowerShell scripts using Nodinite Windows Server Monitoring Agent. Run scripts for monitoring, automation, and secure self-service actions from a single platform.
---

# <i class="fal fa-rectangle-terminal" aria-hidden="true"></i> PowerShell

The <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> [Windows Server Monitoring Agent][] enables you to monitor, automate, and empower users with **custom PowerShell scripts** on your Windows Servers. With this feature, you can run scripts for advanced monitoring, automate routine tasks, and provide secure self-service actions for end-users—all from a single, unified platform.  

✅ Execute virtually any PowerShell script for custom monitoring and automation  
✅ Empower end-users to run scripts as [Remote Actions][] on demand  
✅ Centralize script management and execution for security and compliance  

<aside aria-label="Note" class="nodinite-note nodinite-note--note">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-note"></i> Note</p>
<div class="nodinite-note__content"><p>In <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> <strong>6.4.0.0 and later</strong>, PowerShell monitoring entries and their optional user-action scripts are grouped by identity. Each group shares the same restricted account for PowerShell execution, and sensitive changes to that group require the password for the affected collection.</p><p>For secure deployments, pair that model with TLS-protected transport: prefer HTTPS for remote <a href="https://docs.nodinite.com/logging-and-monitoring/windows-server/features/iis/">IIS</a> hosting and WinRM over HTTPS for remote PowerShell whenever possible.</p><p>Restore behavior: If you restore an older backup where PowerShell group scripts/configurations differ, affected entries can become disabled. Re-enable by making a change in the collection and providing the password for that group.</p></div>
</aside>

## Why Use PowerShell Monitoring?

Built-in monitors (CPU, Memory, [Disk][], IIS) cover common infrastructure scenarios, but **your business logic is unique**. PowerShell monitoring bridges the gap between standard infrastructure monitoring and your specific integration requirements.

**Common scenarios requiring custom scripts:**

* **Integration health checks** - Verify BizTalk orchestrations, message queues, or API endpoint availability
* **Business process validation** - Check file drop locations, database record counts, or scheduled job completion
* **Compliance auditing** - Validate security configurations, certificate expiration, or regulatory requirements
* **Custom application monitoring** - Monitor line-of-business applications without native monitoring support

## What Can You Monitor with PowerShell?

|Monitoring Scenario|Example Script Purpose|State Evaluation|  
|---|---|---|  
|<i class="fal fa-folder" aria-hidden="true"></i> **File System**|Check file age in drop folder, monitor file count|Warning if files older than 2 hours|  
|<i class="fal fa-database" aria-hidden="true"></i> **Database**|Query SQL Server for stuck transactions, row counts|Error if transaction count exceeds threshold|  
|<i class="fal fa-inbox" aria-hidden="true"></i> **Message Queues**|Check MSMQ queue depth, dead-letter queue|Warning if queue depth > 1000 messages|  
|<i class="fal fa-link" aria-hidden="true"></i> **APIs and Web Services**|Test REST API response time, validate endpoints|Error if response time > 5 seconds|  
|<i class="fal fa-briefcase" aria-hidden="true"></i> **Business Rules**|Validate integration data completeness, check SLAs|Warning if daily message count below expected|  
|<i class="fal fa-file-certificate" aria-hidden="true"></i> **Certificates**|Check certificate expiration across multiple stores|Warning 30 days before expiration|  

## When to Use PowerShell vs Built-In Monitors

|Use PowerShell When...|Use Built-In Monitors When...|  
|---|---|  
|Monitoring custom applications or business logic|Monitoring standard Windows infrastructure ([CPU][], [Memory][], [Disk][], [IIS][])|  
|Checking integration-specific conditions (message queues, file drops)|Tracking [Windows Services][], [Event Logs][Windows Server Event Log], or [Scheduled Tasks][]|  
|Combining multiple checks in a single script|Monitoring individual system components|  
|Implementing remediation scripts via [Auto Healing][]|Using standard thresholds without custom logic|  
|Validating business rules or compliance requirements|Checking certificate expiration with standard thresholds|  

**Key advantage:** PowerShell scripts give you **unlimited flexibility** to monitor anything accessible via PowerShell cmdlets, .NET libraries, or external APIs.
<div class="mermaid">
flowchart LR
    A["fa<i class="fal fa-user" aria-hidden="true"></i> Admin"]:::actor
    B["fa<i class="fal fa-code" aria-hidden="true"></i> PowerShell Entry"]:::resource
    C["fa<i class="fal fa-server" aria-hidden="true"></i> Windows Server Monitoring Agent"]:::agent
    D["fa<i class="fal fa-terminal" aria-hidden="true"></i> Script Output"]:::output
    E["fa<i class="fal fa-traffic-light-go" aria-hidden="true"></i> State<br/>OK <br/> Warning <br/> Error <br/> Unavailable"]:::state
    F["fa<i class="fal fa-bolt" aria-hidden="true"></i> Remote Actions<br/>Run Script / View Details"]:::action
    A --> | Configures | B  
    B --> | Monitored by | C  
    C --> | Evaluates | D  
    D --> | Triggers | E  
    E --> | Remote Actions | F  
    classDef agent fill:#2678BD,stroke:#2E5C8A,stroke-width:2px,color:#000
    classDef actor fill:#93d16d,stroke:#2E7D4E,stroke-width:2px,color:#000
    classDef resource fill:#FFD525,stroke:#A67C00,stroke-width:2px,color:#000
    classDef output fill:#c33d34,stroke:#8B2E2E,stroke-width:2px,color:#fff
    classDef state fill:#93d16d,stroke:#2E7D4E,stroke-width:2px,color:#000
    classDef action fill:#2678BD,stroke:#2E5C8A,stroke-width:2px,color:#000
</div>

*Diagram: PowerShell script monitoring flow — user/admin configures a script resource, the <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> Agent evaluates output and maps results to state, and Remote Actions enable execution and troubleshooting.*  

<aside aria-label="Note" class="nodinite-note nodinite-note--note">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-note"></i> Note</p>
<div class="nodinite-note__content"><p>Learn how to utilize your own <strong>PowerShell</strong> scripts for custom monitoring, enabling end-users to execute them through self-service enabled <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> <a href="https://docs.nodinite.com/administration/monitor-management/monitor-views/features/what-is-a-monitor-view/">Monitor Views</a>.</p></div>
</aside>

* ✅ Multi server support: Execute scripts locally or remotely on any Windows Server with the [Monitoring Agent][Monitoring Agents] installed.

<div class="mermaid">
graph LR
    subgraph "fa<i class="fal fa-rectangle-terminal" aria-hidden="true"></i> <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span>"
        roNI["fa<i class="fal fa-monitor-waveform" aria-hidden="true"></i> Windows Server Monitoring Agent"] --- | Local execution | roSRV1["fa<i class="fal fa-server" aria-hidden="true"></i> Server A"]  
    end
    subgraph "Other network"
        roNI --- | Remote execution | roSRV2["fa<i class="fal fa-server" aria-hidden="true"></i> Server B"]  
    end
</div>

*This diagram illustrates how <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> executes PowerShell scripts both locally and remotely, enabling flexible monitoring and automation across your infrastructure.*

<aside aria-label="Note" class="nodinite-note nodinite-note--note">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-note"></i> Note</p>
<div class="nodinite-note__content"><p>You must have <a href="https://learn.microsoft.com/en-us/powershell/scripting/windows-powershell/wmf-overview">WMF 5.1</a><sup><i class="fal fa-arrow-up-right-from-square" aria-hidden="true"></i></sup> or later.<br>
WinRM must be enabled on remote Windows Server if you are using the <strong>PowerShell</strong> feature with a remote target.</p></div>
</aside>

This page outlines how <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> monitors the **PowerShell** [Category][Categories] using one or more [role-based][Roles] [Monitor Views][]. You can configure state evaluation based on user-defined logic—globally or for specific scripts. Remote commands (Actions) are available to help you swiftly address reported problems. All implemented [Remote Actions][] are detailed below.  

![PowerShell items as Resources][1]  
*Example list of monitored 'PowerShell' resources in a [Monitor View][Monitor Views].*

## <i class="fal fa-sliders-h" aria-hidden="true"></i> Monitoring Features

* <i class="fal fa-gears" aria-hidden="true"></i> Administrators manually manage your **PowerShell** configurations. Sharing insights is easy with [Monitor Views][].  
* <i class="fal fa-traffic-light-go" aria-hidden="true"></i> **State Evaluation** – Based on script output: `Write-Warning` for Warnings, `Write-Error` for Errors.  
* <i class="fal fa-folder" aria-hidden="true"></i> **Category-based monitoring** – Group monitored [Resources][] by [Categories][] for streamlined management.  

## <i class="fal fa-traffic-light-go" aria-hidden="true"></i> State evaluation for PowerShell-based monitoring

<span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> displays each monitored PowerShell configuration as a [Resources][]. For example, if you have **2** Windows Server configurations with **2** and **3** PowerShell scripts, you will have **5** 'PowerShell' resources in <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span>.  

* <i class="fal fa-lightbulb-on" aria-hidden="true"></i> The [Resources][] name matches the name of the PowerShell configuration.  
* <i class="fal fa-folder" aria-hidden="true"></i> The 'PowerShell' resource belongs to the following [Category][Categories]:  

|Category|Description|  
|:---:|---|  
|<i class="fal fa-rectangle-terminal" aria-hidden="true"></i> [PowerShell](#fa-rectangle-terminal-powershell-monitoring)|Ensure PowerShell configurations stay within user-defined monitoring thresholds|  

![Categories][2]  
*List of PowerShell-related resources in a [Monitor View][Monitor Views].*

* <i class="fal fa-box-open" aria-hidden="true"></i> The [Application][Applications] name is the **Display Name** of the Windows Server:  
![Application Path Naming Example][5]  
*Example using the [Application][Applications] filter option in a <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> [Monitor View][Monitor Views].*

Each item (presented in <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> as a [Resource][Resources]) is evaluated with a **state**: OK, Warning, Error, or Unavailable.  

You can reconfigure state evaluation at the [Resources][] level using the [Expected State][] feature.  

<aside aria-label="Note" class="nodinite-note nodinite-note--note">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-note"></i> Note</p>
<div class="nodinite-note__content"><p>Depending on the user-defined synchronization interval for the <a href="https://docs.nodinite.com/logging-and-monitoring/windows-server/overview/">Windows Server Monitoring Agent</a>, there may be a <strong>delay</strong> before <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> <a href="https://docs.nodinite.com/getting-started/overview/">Web Client</a>/<a href="https://docs.nodinite.com/administration/monitor-management/monitor-views/features/what-is-a-monitor-view/">Monitor Views</a> reflect changes. Click <strong>Sync All</strong> (or use the dropdown for individual agent selection) to force a resynchronization.</p></div>
</aside>

![Sync option][3]  
*Option to force <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> to request a resynchronization with the Monitoring Agent.*

____________________  

## <i class="fal fa-rectangle-terminal" aria-hidden="true"></i> PowerShell Monitoring

For the **PowerShell** category, <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> evaluates the monitored state as described below:  

|State|Status|Description|<i class="fal fa-bolt" aria-hidden="true"></i> Actions|  
|---|---|---|---|  
|🚫 <span title="Used to indicate an error/fatal condition">Unavailable</span>|**Service not available**|The server can't be reached or evaluated due to network or security issues|Review [prerequisites][Prerequisites for Windows Server Monitoring Agent]|  
|❌ <span title="Used to indicate that an error or abnormal condition has been detected">Error</span>|**Error state raised**|The script fails or contains Write-Error in the output|<i class="fal fa-circle-info" aria-hidden="true"></i> [Details](#fa-circle-info-details)<br/><i class="fal fa-function" aria-hidden="true"></i> [Show Action Scripts](#fa-function-show-action-scripts)|  
|⚠️ <span title="Used to indicate an unexpected but not invalid state">Warning</span>|**Warning state raised**|The script failed or contains Write-Warning in the output|<i class="fal fa-circle-info" aria-hidden="true"></i> [Details](#fa-circle-info-details)<br/><i class="fal fa-function" aria-hidden="true"></i> [Show Action Scripts](#fa-function-show-action-scripts)|  
|✅ <span title="Used to indicate normal operation">OK</span>|**Operational**|The 'PowerShell' configuration is valid, and the script executes without any errors or warnings|<i class="fal fa-circle-info" aria-hidden="true"></i> [Details](#fa-circle-info-details)<br/><i class="fal fa-function" aria-hidden="true"></i> [Show Action Scripts](#fa-function-show-action-scripts)|  

### <i class="fal fa-bolt" aria-hidden="true"></i> Remote Actions for PowerShell

The following [Remote Actions][] are available for the **PowerShell** [Category][Categories]:  

* <i class="fal fa-circle-info" aria-hidden="true"></i> [Details](#fa-circle-info-details)  
* <i class="fal fa-function" aria-hidden="true"></i> [Show Action Scripts](#fa-function-show-action-scripts)  
* <i class="fal fa-bolt" aria-hidden="true"></i> [Execute first](#fa-bolt-execute-first)  
* <i class="fal fa-bolt" aria-hidden="true"></i> [Execute last](#fa-bolt-execute-last)

![PowerShell Remote Actions][4]  
*Available remote actions for the PowerShell category.*

<aside aria-label="Tip" class="nodinite-note nodinite-note--tip">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-lightbulb"></i> Tip</p>
<div class="nodinite-note__content"><p><i class="fal fa-ambulance" aria-hidden="true"></i> Use the <a href="https://docs.nodinite.com/administration/monitor-management/resources/features/auto-healing/">Auto Healing</a> feature to automatically execute remediation scripts based on specific states. This is the main purpose of the 'Execute first' and 'Execute last' actions described below.</p></div>
</aside>

#### <i class="fal fa-circle-info" aria-hidden="true"></i> Details

View details for any **PowerShell** resource by clicking the **Action** button and selecting **Details** in the 'Control Center' section.  

![Details Menu Action][6]  
*Open details modal using the 'Details' action.*  

Next, click the option to open the modal.  

![Details Modal][7]  
*Example of the 'Details' modal.*

#### <i class="fal fa-function" aria-hidden="true"></i> Show Action Scripts

Manage and execute scripts for any **PowerShell** resource by clicking the **Action** button and selecting **Show Action Scripts** in the 'Control Center' section.  

![Show Action Scripts Action][8]  
*Open the scripts modal using the 'Show Action Scripts' action.*  

Next, click the option to open the modal.  

![Show Action Scripts Modal][9]  

*Example of the 'Action Scripts' modal.*  

The scripts modal presents a script collection for the selected PowerShell resource. Key elements in the modal include:

* **Collection title and description** — The modal header shows the collection name (for example, "PowerShell Script Collection Example") and an optional description beneath the Scripts section.  
* **Refresh** — A refresh control in the top-right to request an immediate update of the modal contents.  
* **Scripts list** — A table listing each script with columns for **Name** and **Description**, and an **Execute** button on the right for each entry.  
* **Execute** — Click **Execute** to run the script on the selected target; the user will be prompted to confirm intent before execution.  
* **Output area** — Script output appears at the bottom of the modal after execution.  
* **Close** — Use the Close button to dismiss the modal when finished.  

Click the **Execute** button to run the script on demand.  

![Confirm intent][10]  
*The user must confirm the intent to execute the script.*

The output is presented at the bottom of the modal.  

![PowerShell Script Output][11]  
*Example of the result from the operation.*

#### <i class="fal fa-bolt" aria-hidden="true"></i> Execute first

Execute the first script in the collection immediately from the control menu without opening the full scripts modal. This is a quick-action for running the primary script assigned to the resource. Behavior:

* Prompts the user to confirm the intent before executing.  
* Runs the script on the selected target and appends output to the same output area used by the scripts modal.  
* Use this action when you want to quickly run the top-priority script for the resource.

![Execute first action][47]  
*Execute the 'Execute first' action from the control center menu.*  

#### <i class="fal fa-bolt" aria-hidden="true"></i> Execute last

Execute the last script in the collection immediately from the control menu. This quick-action runs the bottom-most script in the configured script collection. Behavior:

* Prompts the user to confirm the intent before executing.  
* Runs the script on the selected target and appends output to the same output area used by the scripts modal.  
* Use this action when you want to quickly run a secondary or cleanup script defined last in the collection.

![Execute last action][48]  
*Execute the 'Execute last' action from the control center menu.*  

____________________  

## <i class="fal fa-pen-to-square" aria-hidden="true"></i> Configuration

Use [Remote Configuration][WindowsServerConfiguration] to manage **PowerShell** configuration.  

### <i class="fal fa-rectangle-terminal" aria-hidden="true"></i> PowerShell tab

Click the **PowerShell** tab to manage PowerShell monitoring options.  
![PowerShell tab][40]  
*Example of the 'PowerShell' configuration tab.*  

|State|Example code|Description|  
|:---:|---|---|  
|✅ <span title="Used to indicate normal operation">OK</span>|echo "Hello World"|Script runs without errors and has no warnings or errors written to the output|  
|⚠️ <span title="Used to indicate an unexpected but not invalid state">Warning</span>|Write-Warning "Warning for moderate rain"|Script runs without errors and has a warning written to the output|  
|❌ <span title="Used to indicate that an error or abnormal condition has been detected">Error</span>|Write-Error "General failure reading from disk"|Script fails or has errors written to the output|  

<aside aria-label="Important" class="nodinite-note nodinite-note--important">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-message-exclamation"></i> Important</p>
<div class="nodinite-note__content"><p><strong>Output Formatting for Objects and Tables</strong>: All PowerShell operations that return objects, tables, or non-string results <strong>SHOULD</strong> use <code>| Out-String</code> to ensure proper output formatting in <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span>.</p><p><strong>Examples requiring <code>| Out-String</code>:</strong></p><pre><code class="language-powershell"># Table results
Get-Process | Select-Object -First 5 | Out-String  
&#10;# Object properties
Get-Service -Name "Spooler" | Format-List | Out-String  
&#10;# System information
Get-ComputerInfo | Select-Object CsName, OsVersion | Out-String  
</code></pre><p>Without <code>| Out-String</code>, object output may not display correctly in the <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> <a href="https://docs.nodinite.com/getting-started/overview/">Web Client</a> or <a href="https://docs.nodinite.com/getting-started/monitor/remote-actions/">Remote Actions</a> results.</p></div>
</aside>

Click the <i class="fal fa-square-plus" aria-hidden="true"></i> **Add** button to add a new entry. This will become the Resource as seen in [Monitor Views][].  

#### PowerShell General tab

This is the monitoring entry.  

* <i class="fal fa-toggle-on" aria-hidden="true"></i> **Enabled** – When checked, this PowerShell Script is monitored  
* <i class="fal fa-tag" aria-hidden="true"></i> **Display Name** – The user-friendly name of this resource as provided to end-users within Monitor Views  
* <i class="fal fa-align-left" aria-hidden="true"></i> **Description** – User-friendly description for the PowerShell Script resource  
* <i class="fal fa-rectangle-terminal" aria-hidden="true"></i> **PowerShell Script** – The script to use for monitoring  
![PowerShell General tab][42]  
*Example of the PowerShell configuration General tab.*  

#### <i class="fal fa-user-ninja" aria-hidden="true"></i> User Action Scripts

This entry allows the System Administrator to provide a script collection for end-users with permission to execute content as [Remote Actions][].  
![PowerShell User Script Collection tab][43]  
*Example of the PowerShell User Script Collection tab.*

Click the <i class="fal fa-square-plus" aria-hidden="true"></i> **Add** button for each script to include in the script collection.  
![User script entry][44]  
*Example of a PowerShell User Script entry.*

#### PowerShell Authentication

Set authentication options for executing the PowerShell script.  
![Authentication tab][45]  
*Example of the PowerShell configuration Authentication tab.*  

Check the checkbox to execute the script on another target host.  

* <i class="fal fa-server" aria-hidden="true"></i> **Is remote server** – When checked, these PowerShell Scripts run on a remote server.  
  * <i class="fal fa-network-wired" aria-hidden="true"></i> **Address** – The address for the remote server.  
* <i class="fal fa-shield-halved" aria-hidden="true"></i> **Use authentication** – When checked, authenticate to the remote server or impersonate a user locally via the username and password fields below.  
  * <i class="fal fa-user" aria-hidden="true"></i> **Domain User** – The name of the Windows user account. Format: DOMAIN\User.  
  * <i class="fal fa-key" aria-hidden="true"></i> **Password** – The password for the provided domain user.  

![Authentication fields][46]  
*Example of the PowerShell configuration Authentication fields.*

____________________  

## <i class="fal fa-code" aria-hidden="true"></i> PowerShell Script Examples

Below are practical examples demonstrating state evaluation and proper output formatting for common monitoring scenarios.

### <i class="fal fa-circle-check" aria-hidden="true"></i> Example 1: Simple OK State

Returns a success message without warnings or errors:

```powershell
# Monitor disk space - OK state
$drive = Get-PSDrive C
$freeSpaceGB = [math]::Round($drive.Free / 1GB, 2)

Write-Output "Drive C: has $freeSpaceGB GB free space available"
```

**Expected State**: ✅ OK

### <i class="fal fa-exclamation-triangle" aria-hidden="true"></i> Example 2: Warning State

Triggers a warning when a threshold is approached:

```powershell
# Monitor disk space - Warning when below 20%
$drive = Get-PSDrive C
$freeSpacePercent = [math]::Round(($drive.Free / $drive.Used) * 100, 2)

if ($freeSpacePercent -lt 20) {
    Write-Warning "Drive C: is running low on space: $freeSpacePercent% free"
} else {
    Write-Output "Drive C: has sufficient space: $freeSpacePercent% free"
}
```

**Expected State**: ⚠️ Warning (when below 20%)

### <i class="fal fa-times-circle" aria-hidden="true"></i> Example 3: Error State

Triggers an error when a critical threshold is exceeded:

```powershell
# Monitor disk space - Error when below 10%
$drive = Get-PSDrive C
$freeSpacePercent = [math]::Round(($drive.Free / $drive.Used) * 100, 2)

if ($freeSpacePercent -lt 10) {
    Write-Error "CRITICAL: Drive C: is critically low on space: $freeSpacePercent% free"
} elseif ($freeSpacePercent -lt 20) {
    Write-Warning "Drive C: is running low on space: $freeSpacePercent% free"
} else {
    Write-Output "Drive C: has sufficient space: $freeSpacePercent% free"
}
```

**Expected State**: ❌ Error (when below 10%)

### <i class="fal fa-table" aria-hidden="true"></i> Example 4: Table Output with Out-String

Displays service status in a formatted table (demonstrates `| Out-String`):  

```powershell
# Monitor multiple Windows Services with table output
$services = @('W3SVC', 'WinRM', 'MSSQLSERVER')
$results = foreach ($serviceName in $services) {
    $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue

    if ($null -eq $service) {
        [PSCustomObject]@{
            Service = $serviceName
            Status = 'NotFound'
            State = 'Error'
        }
        Write-Error "Service '$serviceName' not found on this server"
    } elseif ($service.Status -ne 'Running') {
        [PSCustomObject]@{
            Service = $serviceName
            Status = $service.Status
            State = 'Warning'
        }
        Write-Warning "Service '$serviceName' is not running (Status: $($service.Status))"
    } else {
        [PSCustomObject]@{
            Service = $serviceName
            Status = $service.Status
            State = 'OK'
        }
    }
}

# Output table with proper formatting
$results|Format-Table -AutoSize|Out-String
```

**Expected State**: Varies based on service status (OK if all running, Warning/Error otherwise)  
**Key Point**: `| Out-String` ensures the table displays correctly in <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> [Web Client][]  

### <i class="fal fa-server" aria-hidden="true"></i> Example 5: System Information with Out-String

Retrieves system information with proper formatting:

```powershell
# Monitor server uptime and basic info
$os = Get-CimInstance -ClassName Win32_OperatingSystem
$uptime = (Get-Date) - $os.LastBootUpTime

$info = [PSCustomObject]@{
    ServerName = $env:COMPUTERNAME
    'Uptime (Days)' = [math]::Round($uptime.TotalDays, 2)
    'OS Version' = $os.Caption
    'Free Memory (GB)' = [math]::Round($os.FreePhysicalMemory / 1MB, 2)
}

# Check if uptime is too long (e.g., > 90 days)
if ($uptime.TotalDays -gt 90) {
    Write-Warning "Server has not been rebooted in $([math]::Round($uptime.TotalDays, 0)) days"
}

# Output formatted information
$info|Format-List|Out-String
```

**Expected State**: ⚠️ Warning (if uptime > 90 days)  
**Key Point**: `| Out-String` formats object properties for readable output  

### <i class="fal fa-list-check" aria-hidden="true"></i> Example 6: Multiple Checks with Combined States

Performs multiple checks and combines state evaluation:

```powershell
# Comprehensive server health check
$errorCount = 0
$warningCount = 0

# Check 1: CPU Usage
$cpu = Get-CimInstance Win32_Processor|Measure-Object -Property LoadPercentage -Average
if ($cpu.Average -gt 90) {
    Write-Error "CPU usage is critically high: $($cpu.Average)%"
    $errorCount++
} elseif ($cpu.Average -gt 70) {
    Write-Warning "CPU usage is elevated: $($cpu.Average)%"
    $warningCount++
}

# Check 2: Memory Usage
$os = Get-CimInstance Win32_OperatingSystem
$memoryUsedPercent = [math]::Round((($os.TotalVisibleMemorySize - $os.FreePhysicalMemory) / $os.TotalVisibleMemorySize) * 100, 2)
if ($memoryUsedPercent -gt 95) {
    Write-Error "Memory usage is critically high: $memoryUsedPercent%"
    $errorCount++
} elseif ($memoryUsedPercent -gt 85) {
    Write-Warning "Memory usage is elevated: $memoryUsedPercent%"
    $warningCount++
}

# Check 3: Critical Services
$criticalServices = @('W3SVC', 'WinRM')
foreach ($serviceName in $criticalServices) {
    $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
    if ($null -eq $service -or $service.Status -ne 'Running') {
        Write-Error "Critical service '$serviceName' is not running"
        $errorCount++
    }
}

# Summary output
$summary = [PSCustomObject]@{
    'Server' = $env:COMPUTERNAME
    'CPU Usage %' = $cpu.Average
    'Memory Usage %' = $memoryUsedPercent
    'Errors' = $errorCount
    'Warnings' = $warningCount
}

$summary|Format-List|Out-String

if ($errorCount -eq 0 -and $warningCount -eq 0) {
    Write-Output "All health checks passed successfully"
}
```

**Expected State**: Varies based on multiple conditions  
**Key Point**: Demonstrates combining multiple checks with proper state evaluation and formatted output

____________________  

## <i class="fal fa-hand-point-right" aria-hidden="true"></i> Next Steps

* <i class="fal fa-display" aria-hidden="true"></i> [Add or manage Monitor View][]  

## <i class="fal fa-link-horizontal" aria-hidden="true"></i> Related Topics

* <i class="fab fa-windows" aria-hidden="true"></i> [Windows Server Monitoring Agent][]  
* <i class="fal fa-lightbulb-on" aria-hidden="true"></i> [Resources][]  
* <i class="fal fa-cloud-arrow-down" aria-hidden="true"></i> [Monitoring][]  
* <i class="fal fa-display" aria-hidden="true"></i> [Monitor Views][]  
* <i class="fal fa-shield-halved" aria-hidden="true"></i> [How to run custom PowerShell scripts securely][PowerShell Security Best Practices]  
* <i class="fal fa-database" aria-hidden="true"></i> [SQL Server - SQL Statements][]  - Similar monitoring approach using custom TSQL scripts  
* <i class="fal fa-server" aria-hidden="true"></i> [How to Monitor a Clustered Windows Service][]  - PowerShell example for clustered service monitoring  

[1]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/WindowsServer/PowerShell/PowerShellResourcesInMonitorView.png
[2]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/WindowsServer/PowerShell/PowerShellCategories.png
[3]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/WindowsServer/IIS/SyncAllMenuItemButton.png
[4]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/WindowsServer/PowerShell/Actions.png
[5]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/WindowsServer/PowerShell/ApplicationFilter.png
[6]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/WindowsServer/PowerShell/DetailsMenuItem.png
[7]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/WindowsServer/PowerShell/DetailsModal.png
[8]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/WindowsServer/PowerShell/ShowActionScriptMenuItem.png
[9]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/WindowsServer/PowerShell/ActionScriptsModal.png
[10]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/WindowsServer/PowerShell/ConfirmExecuteScript.png
[11]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/WindowsServer/PowerShell/ExecuteScriptOutput.png
[40]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/WindowsServer/RemoteConfig/PowerShellTab.png
[42]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/WindowsServer/PowerShell/GeneralTab.png
[43]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/WindowsServer/PowerShell/UserActionScriptTab.png
[44]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/WindowsServer/PowerShell/UserActionScript.png
[45]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/WindowsServer/PowerShell/AuthenticationTab.png
[46]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/WindowsServer/PowerShell/AuthenticationFields.png
[47]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/WindowsServer/PowerShell/ActionExecuteFirst.png
[48]:https://docs.nodinite.com/media/Documentation%20Pictures/MonitorAgent/WindowsServer/PowerShell/ActionExecuteLast.png

[Add or manage Monitor View]:https://docs.nodinite.com/administration/monitor-management/monitor-views/features/add-or-manage-monitor-view/
[Applications]:https://docs.nodinite.com/administration/monitor-management/applications/features/what-is-an-application/
[Auto Healing]:https://docs.nodinite.com/administration/monitor-management/resources/features/auto-healing/
[Categories]:https://docs.nodinite.com/administration/monitor-management/categories/features/what-is-a-category/
[CPU]:https://docs.nodinite.com/logging-and-monitoring/windows-server/features/cpu/
[Disk]:https://docs.nodinite.com/logging-and-monitoring/windows-server/features/disk/
[Expected State]:https://docs.nodinite.com/administration/monitor-management/resources/features/expected-state/
[How to Monitor a Clustered Windows Service]:https://docs.nodinite.com/logging-and-monitoring/windows-server/troubleshooting/how-to-monitor-a-clustered-windows-service/
[IIS]:https://docs.nodinite.com/logging-and-monitoring/windows-server/features/iis/
[Memory]:https://docs.nodinite.com/logging-and-monitoring/windows-server/features/memory/
[Monitor Views]:https://docs.nodinite.com/administration/monitor-management/monitor-views/features/what-is-a-monitor-view/
[Monitoring]:https://docs.nodinite.com/monitoring/
[Monitoring Agents]:https://docs.nodinite.com/administration/monitor-management/monitor-agents/features/what-is-a-monitor-agent/
[PowerShell Security Best Practices]:https://docs.nodinite.com/logging-and-monitoring/windows-server/troubleshooting/how-to-run-custom-powershell-scripts-securely/
[Prerequisites for Windows Server Monitoring Agent]:https://docs.nodinite.com/logging-and-monitoring/windows-server/getting-started/prerequisites/
[Remote Actions]:https://docs.nodinite.com/getting-started/monitor/remote-actions/
[Resources]:https://docs.nodinite.com/administration/monitor-management/resources/features/what-is-a-resource/
[Roles]:https://docs.nodinite.com/administration/access-management/roles/features/what-is-a-role/
[Scheduled Tasks]:https://docs.nodinite.com/logging-and-monitoring/windows-server/features/scheduled-tasks/
[SQL Server - SQL Statements]:https://docs.nodinite.com/logging-and-monitoring/database/features/sql-statements/sql-server-statements/
[Web Client]:https://docs.nodinite.com/getting-started/overview/
[Windows Server Event Log]:https://docs.nodinite.com/logging-and-monitoring/windows-server/features/event-log/
[Windows Server Monitoring Agent]:https://docs.nodinite.com/logging-and-monitoring/windows-server/overview/
[Windows Services]:https://docs.nodinite.com/logging-and-monitoring/windows-server/features/windows-services/
[WindowsServerConfiguration]:https://docs.nodinite.com/logging-and-monitoring/windows-server/getting-started/configuration/