I am not a Powershell master, I am making myself a favor by calling myself a beginner.
Requirement arose such that I had to write one to query a service on 400 hosts and I found it very much necessary to script it.
Of course , Powershell is much more organized then the batch scripting(though I haven't done much there either)
Below script will Read from the a text file "serverlist.txt" , the list of windows 2008 servers.
$serverlist=Get-Content("serverlist.txt")
$ping = new-object System.Net.NetworkInformation.Ping
foreach ($server in $serverlist)
{
if ($ping.Send($server).status -eq "Success")
{
Start-Sleep -Seconds 10
try
{
$ErrorActionPreference = "silentlycontinue"
$status=Get-WmiObject -Class win32_service -ComputerName $server | ?{$_.name-like "tmlisten" } | % {"$($_.name) is $($_.state)"}
if($?)
{
if ( $status -eq "tmlisten is Running")
{
echo "$server,$status"
}
elseif ($status -eq "tmlisten is Stopped")
{
(Get-WmiObject -computer $server Win32_Service -Filter "Name='tmlisten'").InvokeMethod("StartService")
Start-Sleep -Seconds 30
Get-WmiObject -Class win32_service -ComputerName $server | ?{$_.name-like "tmlisten" } | % {"$server,$($_.name) is $($_.state)"}
}
} else
{
echo "$server,RPC service Connectivity issues."
}
}catch
{
echo " $server,Exception occured while quering server."
}
}
else
{
echo "$server,Cant ping the server"
}
}
I am querying for a service "tmlisten".
This wonderful one liner put me in the right direction
Thanks a a million to the author as I was desperately looking for a solution.
No comments:
Post a Comment