Solved

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

Posted on 2016-11-14
8
43 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
 
LVL 35

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
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
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 35

Expert Comment

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

Featured Post

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

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

This article will help you understand what HashTables are and how to use them in PowerShell.
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This tutorial will walk an individual through the process of transferring the five major, necessary Active Directory Roles, commonly referred to as the FSMO roles from a Windows Server 2008 domain controller to a Windows Server 2012 domain controlle…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

863 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

23 Experts available now in Live!

Get 1:1 Help Now