Solved

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

Posted on 2016-11-14
8
74 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 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 7

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 83

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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 36

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 7

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 83

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 7

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 36

Expert Comment

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

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

This article runs through the process of deploying a single EXE application selectively to a group of user.
The following article is intended as a guide to using PowerShell as a more versatile and reliable form of application detection in SCCM.
The viewer will learn how to dynamically set the form action using jQuery.
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

813 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