Solved

Need  help in modifying Powershell script to list service with specific pattern and its status ?

Posted on 2016-11-14
8
31 Views
Last Modified: 2016-11-15
Hi All,

Can anyone here please assist me in modifying the Powershell script below so that it can go through the list of servers within the specific OU and then list all of the service with the name that has the keyword " *Application 1*" along with the server name, service name, service running status, Startup Status and the service account running  ?

Because there are about 3-4 services per server with the keyword " *Application 1*" like:

Application 1 Watcher
Application 1 Server
Application 1 Updater


$path = "C:\TEMP\"
$serverlist = Get-ADComputer -Properties Name -Filter {Enabled -eq $True -and OperatingSystem -like "*Windows Server*"} -SearchBase "OU=Servers,DC=domain,DC=com" |
  Where-Object {$_.DistinguishedName -notlike "*OU=Decommissioned Servers,OU=Servers,DC=domain,DC=com"} |
  Where-Object {Test-Connection $_.Name -Count 1 -Quiet}

$servicename = "Application 1"

foreach ($server in $serverlist){
		$servicetorestart = Get-Service -name -Include $servicename -ComputerName $server.Name -ErrorAction SilentlyContinue
		......
		# what else to fill in here
		......
} | Export-Csv -Path $path -NoClobber -NoTypeInformation -UseCulture

Open in new window


Any help would be greatly appreciated.

Thanks in advance,
0
Comment
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 16

Assisted Solution

by:Learnctx
Learnctx earned 100 total points
Comment Utility
Use Get-WmiObject instead of Get-Service or you'll have to parse every service from every server. WQL will allow you to filter on the remote server without returning all the servers to be processed on your end.

Get-WmiObject -Query "SELECT Name, DisplayName, State, StartMode, StartName FROM Win32_Service WHERE DisplayName LIKE '%$($servicename)%'"

Open in new window

1
 
LVL 7

Author Comment

by:Senior IT System Engineer
Comment Utility
Hi LearnCTX,

I have modified it into:

$path = "C:\TEMP\"
$serverlist = Get-ADComputer -Properties Name -Filter {Enabled -eq $True -and OperatingSystem -like "*Windows Server*"} -SearchBase "OU=Servers,DC=domain,DC=com" |
  Where-Object {$_.DistinguishedName -notlike "*OU=Decommissioned Servers,OU=Servers,DC=domain,DC=com"} |
  Where-Object {Test-Connection $_.Name -Count 1 -Quiet}

$servicename = "HP Insight"

foreach ($server in $serverlist){
		$Servicelists = Get-WmiObject -Query "SELECT Name, DisplayName, State, StartMode, StartName FROM Win32_Service WHERE DisplayName LIKE '%$($servicename)%'"
} 

$Servicelists | Export-Csv -Path $path\ResultSVC.csv -NoClobber -NoTypeInformation -UseCulture

Open in new window


But somehow there is no error and the .CSV result is empty 0 KB file size ?
0
 
LVL 82

Accepted Solution

by:
oBdA earned 300 total points
Comment Utility
Try it like this:
$path = "C:\TEMP"
$ServiceName = "HP Insight"
$SearchBase = "OU=Servers,DC=domain,DC=com"
$Properties = 'Name', 'DisplayName', 'State', 'StartMode', 'StartName'

$ServerList = Get-ADComputer -Properties Name -Filter {Enabled -eq $True -and OperatingSystem -like "*Windows Server*"} -SearchBase $SearchBase |
	Where-Object {$_.DistinguishedName -notlike "*OU=Decommissioned Servers,OU=Servers,DC=domain,DC=com"}

$ServiceList = ForEach ($Server in $ServerList) {
	$(Try {
		Write-Host "Processing $($Server.Name) ..." -ForegroundColor White -NoNewline
		If (-not (Test-Connection -ComputerName $Server.DNSHostName -Count 1 -Quiet)) {
			Throw "Offline"
		}
		Get-WmiObject -Query "SELECT $($Properties -join ',') FROM Win32_Service WHERE DisplayName LIKE '%$($ServiceName)%'" -ErrorAction Stop -ComputerName $Server.DNSHostName
		$Exception = $Null
		Write-Host " OK." -ForegroundColor Green
	} Catch {
		$Exception = $_.Exception.Message
		''
		Write-Host " $($Exception)" -ForegroundColor Red
	}) | Select-Object -Property (@(@{n='ComputerName'; e={$Server.Name}}) + $Properties + @{n='Exception'; e={$Exception}})
}

$ServiceList | Export-Csv -Path $path\ResultSVC.csv -NoClobber -NoTypeInformation -UseCulture

Open in new window

1
 
LVL 35

Assisted Solution

by:Mahesh
Mahesh earned 100 total points
Comment Utility
Try below code:

$datetime = Get-Date -Format DDMMYYY_HHmm
$Scriptdir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
$ServerTest = $Scriptdir + "\ServertestReport_$datetime.txt"
$ExportFilepath = $ScriptDir + "\ServiceStatus_$DateTime.csv"
$serverlist = Get-ADComputer -Filter {(Enabled -eq $True) -and (OperatingSystem -like "*Windows Server*")} -SearchBase "OU=Servers,DC=domain,DC=com" | ?{$_.DistinguishedName -notlike "*OU=Decommissioned Servers,OU=Servers,DC=domain,DC=com"}
  
foreach ($server in $serverlist) {
        if (Test-Connection -ComputerName $($server.DNSHostName) -Count 1 -Quiet)
        { "$($Server.DNSHostname), Contacted successfully" | Out-File $ServerTest -Append -Force
        $services = Get-WmiObject Win32_Service -ComputerName $($server.DNSHostName) -ErrorAction SilentlyContinue | ?{$_.DisplayName -match "Application 1"}
        $services | Select-Object Name, DisplayName, State, Status, StartName, SystemName, StartMode | Export-Csv -Path $ExportFilepath -NoTypeInformation
       }
       else { 
                "$($Server.DNSHostname), failed to connect" | Out-File $ServerTest -Append -Force 
            }
    }

Open in new window

1
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 7

Author Comment

by:Senior IT System Engineer
Comment Utility
Many thanks for the suggestion and the codes people,

However in some of the Windows Server 2012 R2 VMs, I get:

The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

is it because the service is non existent or is it because of the Symantec Firewall ?
0
 
LVL 82

Expert Comment

by:oBdA
Comment Utility
That's probably because of the Firewall then. The error means that the WMI query failed, so it didn't even get access to query the services.
1
 
LVL 7

Author Closing Comment

by:Senior IT System Engineer
Comment Utility
Thanks All for the suggestion and the solution.

OBDA solution works great.

Mahesh, your script is partially works:
result filename is ServiceStatus_DD11YYYY_0938.csv and the content is not showing when modifying the line
 $services = Get-WmiObject Win32_Service -ComputerName $($server.DNSHostName) -ErrorAction SilentlyContinue | ?{$_.DisplayName -like "HP Insight"}
0
 
LVL 35

Expert Comment

by:Mahesh
Comment Utility
you need to use
?{$_.DisplayName -match "HP Insight"}
1

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

This article will help you understand what HashTables are and how to use them in PowerShell.
This article explains how to prepare an HTML email signature template file containing dynamic placeholders for users' Azure AD data. Furthermore, it explains how to use this file to remotely set up a department-wide email signature policy in Office …
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now