Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Assistance cleaning up a script please

$
0
0

Hi all,

I run a script to collect servers and list Auto services that are stopped.  It will also show which server is not responding.  The results though are done as it checks each server. This can lead to a pretty messy layout.

Script:

$Servers = Get-Content Servers.txt
$ErrorActionPreference = "Stop"
ForEach ( $Server in $Servers ) {
	If (Test-Connection $Server -Count 1 -Quiet) {
		$Result = $Null
		Try {
			$Result = Get-WmiObject win32_service -computername $Server | Where-Object {$_.StartMode -eq "Auto" -and $_.State -eq "Stopped" } | Select-Object SystemName,DisplayName,StartMode,State
			If ($Result -eq $Null) {
				Write-Host "$Server has no failed services" -ForegroundColor Green
			}
			Else {
				$Result
			}
		}
		Catch {
			Write-Host "$Server firewall rules are preventing communication to this server" -ForegroundColor Red
		}
	}
	Else {
		Write-Host "$Server is not responding to ICMP" -ForegroundColor Red
	}
}

Result:

SRVIIS01 has no failed services
SRVTYA01 has no failed servicesSRVEXA02 firewall rules are preventing communication to this server
SRVARR01 has no failed services
SRVSQL02 has no failed servicesSRVAVZ01 firewall rules are preventing communication to this server
SRVAZF01 has no failed services
SRVZAF02 has no failed services
SRVEXF03 has no failed servicesSRVEXV01 firewall rules are preventing communication to this server
SRVEXV02 has no failed services
SRVEXV03 has no failed services

SystemName                    DisplayName                   StartMode                     State
----------                    -----------                   ---------                     -----
SRVNAS01                 Sample Service             Auto                          Stopped
SRVSRM001 has no failed services
SRVFWS001 is not responding to ICMP
SRVFWS005 is not responding to ICMP
SRVFWS006 is not responding to ICMP
SRVNAS002                 Sample Service             Auto                          Stopped

Ideally I would like to group together the results so list all that have no failed services, then failed and finally servers with stopped services.
I tried doing this by putting the results into an array and then outputting all three arrays at the end but I failed pretty badly.

I was thinking about using  New-Object PSObject to make the results fit nicely under a table but wasn't sure if I can colour my text by result. Is this possible?


Viewing all articles
Browse latest Browse all 21975

Trending Articles