ShannonCallahan
asked on
Cleaning up Powershell Scipt for Service restart.
Hello!
I am trying to figure out the best way to do the following. I want to set the startup type of System Event Notification Service (SENS) to Automatic, then check to see if it was set correctly, display a message of either success or unsuccessful, followed by restarting the service. Currently I have:
However, I was told that this is sloppy. How could I make this cleaner?
Thank you!
Shannon
I am trying to figure out the best way to do the following. I want to set the startup type of System Event Notification Service (SENS) to Automatic, then check to see if it was set correctly, display a message of either success or unsuccessful, followed by restarting the service. Currently I have:
# Set SENS Service StartupType to Automatic
write-Host "Setting System Event Notification Service Startup Type to Automatic on $ComputerName..." -ForegroundColor 'White'
Try {Set-Service -Name SENS -StartupType Automatic}
Catch {$TimeStamp = (Get-Date).ToUniversalTime()
[void]$ErrorList.add($ErrorMessage)
Write-Host "Could not set System Event Notification Service Startup Type to Automatic on $ComputerName. Exception Error: $($_.Exception.Message)" -ForegroundColor 'Red'}
#Check is SENS service is set to automatic
$SENService = Get-Service -Name SENS
If ($SENService.StartType -eq "Automatic") {Write-host "System Event Notification Service is set to Automatic on $ComputerName..."}
If ($SENService.StartType -ne "Automatic"){Write-Host "System Event Notification Service is not set to Automatic on $ComputerName..."}
# Restart SENS Service
Write-Host "Restarting System Event Notification Service on $ComputerName..." -ForegroundColor 'White'
$Error.clear()
Try {Restart-Service -Name SENS -Force -ErrorAction Stop}
Catch {$TimeStamp = (Get-Date).ToUniversalTime()
[void]$ErrorList.add($ErrorMessage)
Write-Host "Exception Error: $($_.Exception.Message)" -ForegroundColor 'Red'
Write-Host "Could not Restart System Event Notification Service on $ComputerName. Exception Error: $($_.Exception.Message)" -ForegroundColor 'Red'}
If (!$Error) {Write-Host "Restarted System Event Notification Service!" -ForegroundColor 'Green'}
However, I was told that this is sloppy. How could I make this cleaner?
Thank you!
Shannon
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER