Link to home
Start Free TrialLog in
Avatar of ShannonCallahan
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:

# 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'}

Open in new window


However, I was told that this is sloppy. How could I make this cleaner?

Thank you!
Shannon
ASKER CERTIFIED SOLUTION
Avatar of Dustin Saunders
Dustin Saunders
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ShannonCallahan
ShannonCallahan

ASKER

I missed defining the $ComputerName here, I will keep that in mind for future posts. I had them send me how they would do it. The changes were preferential. I did change the IF IF statement to an IF Then statement. Thank you for your response!