Solved

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

Posted on 2016-11-14
8
85 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 17

Assisted Solution

by:Learnctx
Learnctx earned 100 total points
ID: 41887347
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 8

Author Comment

by:Senior IT System Engineer
ID: 41887363
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 84

Accepted Solution

by:
oBdA earned 300 total points
ID: 41887405
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
Major Incident Management Communications

Major incidents and IT service outages cost companies millions. Often the solution to minimizing damage is automated communication. Find out more in our Major Incident Management Communications infographic.

 
LVL 37

Assisted Solution

by:Mahesh
Mahesh earned 100 total points
ID: 41888392
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
 
LVL 8

Author Comment

by:Senior IT System Engineer
ID: 41888842
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 84

Expert Comment

by:oBdA
ID: 41888850
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 8

Author Closing Comment

by:Senior IT System Engineer
ID: 41888889
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 37

Expert Comment

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

Featured Post

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The Windows functions GetTickCount and timeGetTime retrieve the number of milliseconds since the system was started. However, the value is stored in a DWORD, which means that it wraps around to zero every 49.7 days. This article shows how to solve t…
A hard and fast method for reducing Active Directory Administrators members.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

739 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