Error trapping while stopping/starting services in powershell

  • Marios Philippopoulos

    SSC Guru

    Points: 57030

    Hi,

    Is the following code OK for trapping errors while stopping/starting services in powershell scripts?

    How can it be improved?

    $computer = "myComputer"

    $instance = "myComputer\myInstance"

    $service = "SQLAGENT`$myInstance"

    function getService ( [string]$Computer, [string]$Service )

    {

    $oldErrCount = $error.Count

    $query = "select * from Win32_Service where Name='" + $Service + "'"

    trap { continue }

    get-wmiobject -ComputerName $Computer -query $query -ea SilentlyContinue

    if ($error.Count -ne $oldErrCount)

    {

    return $null

    }

    }

    $S = getService $computer $service

    if ($S -eq $null)

    {

    $error = 'Error in step: Stop ' + $instance + ' SQL Agent Service'

    Write-Output $error

    break

    }

    else

    {

    $msg = 'Stopping ' + $instance + ' SQL Agent Service...'

    Write-Output $msg

    $S.StopService()

    }

    __________________________________________________________________________________
    SQL Server 2016 Columnstore Index Enhancements - System Views for Disk-Based Tables[/url]
    Persisting SQL Server Index-Usage Statistics with MERGE[/url]
    Turbocharge Your Database Maintenance With Service Broker: Part 2[/url]

  • Mike - CI

    SSCarpal Tunnel

    Points: 4146

    I think what you have will work just fine. However this is a good article on doing some error trapping in powershell. Perhaps you can get some extra tips from it.

    http://powershell.com/cs/blogs/tobias/archive/2008/09/29/trapping-errors.aspx

  • Marios Philippopoulos

    SSC Guru

    Points: 57030

    Mike (3/23/2009)


    I think what you have will work just fine. However this is a good article on doing some error trapping in powershell. Perhaps you can get some extra tips from it.

    http://powershell.com/cs/blogs/tobias/archive/2008/09/29/trapping-errors.aspx

    Thank you! I'll have a look.

    __________________________________________________________________________________
    SQL Server 2016 Columnstore Index Enhancements - System Views for Disk-Based Tables[/url]
    Persisting SQL Server Index-Usage Statistics with MERGE[/url]
    Turbocharge Your Database Maintenance With Service Broker: Part 2[/url]

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply