Get-Service AppHostSVC,FTPSVC,IISAdmin,MSFTPSVC,W3SVC,WAS,WMSVC |
Select Name,Status,DisplayName|
Where-Object {$_.Status -EQ "Stopped"}
ConvertTo-Html |
Out-File -FilePath c:\checker.html
In the above cmdlet, how can I add a conditional file creation? I need the file to be created only when the said service are in STOPPED status.
NOTE: mklement()'s answer is much better and with proper explanation.
You should place all the services' names in a file or something. You can read the file using get-content
Then you can iterate each of the services names by using a foreach
loop.
For each of the services, you can check the service's status and based on that you can decide to write that in file or not.
Now note by, I have just given a simplified structure of what you were trying to achieve but since I am not sure whether you want the content to be appended in the same file or the file has to be overwritten or something similar; I just gave a simple statement so that you get the logic.
Further I'd like you to put try/catch
block and capture the error because most of the services wont be readily available. So, it is always better to capture the error message or at least the exception message in the catch block.
Also note, in case of nothing returned, then you can just put a file creation statement in the else block which will help you. It means that service is not stopped hence the file is being created as empty or may be you should just add the service name as the content of the file to know specifically which service corresponds to it.
You should do something like this:
try
{
$services = "AppHostSVC","FTPSVC", "IISAdmin"
foreach($service in $services)
{
if((Get-Service $Service).Status -eq 'Stopped')
{
Get-Service $Service| Select-Object Name,Status,DisplayName| ConvertTo-Html |Out-File -FilePath "C:\checker.html" -Append -Force
}
else
{
"$($Service) is not stopped"
}
}
}
catch
{
$_.Exception.Message
}
Hope it helps.