Error trapping while stopping/starting services in powershell

  • 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]

  • 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

  • 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 2 (of 2 total)

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