Sunday, 8 September 2013

Differentiate service state

Differentiate service state

I am trying to import a text file with service names, start the services
that are in a Stopped state and then output the result to a text file.
Importing and starting the services was not a problem. However, in the
final text file I want to differentiate between services that had the
Started state to begin with.
In the end I want a text file with a list of the services with:
service 1 Started by script
service 2 Started
service 3 And so on...
My idea was to was to import the text file, check the state and output
that to a new text file. Then I would change Stopped to Started by script.
However, I can't always guarantee that the service starts, so this would
be a quick and dirty method.
Full code:
$importedFile = cat C:\services.txt #Import .txt file
Write-Host "Listing services..." -for Yellow
$formatStatus = foreach ($_ in $importedFile){ #Format
imported .txt file
gwmi -Class Win32_Service -Filter "Name='$_'" | select Name,State,Displayname
};$formatStatus | sort Name
$stoppedCount = $formatStatus.State -eq "Stopped" | measure #Count
amount of stopped services
Write-Host `n"There are $($stoppedCount.Count) stopped services in this
list!"`n -for Yellow
do{
$startService = Read-Host "Do you want to start these
$($stoppedCount.Count) services? [Y/N]"
} until($startService -eq "Y" -or $startService -eq "N")
if($startService -eq "Y"){ #EDIT
if ($formatStatus.State -eq 'Stopped'){
$formatStatus| sasv
}
}
if($startService -eq "N"){
Write-Host "Exiting without starting services..." -for red;
start-sleep -s 2;exit
}
Is there a way to differentiate between these two?

No comments:

Post a Comment