Powershell script: Stop and Start BizTalk Services

Script to stop or start IIS and Biztalk services on local computer
Must be run with elevated rigths to stop services

#   ------------------------------------------------------------------
#   ------------------------------------------------------------------
#   Author: Peter Lykkegaard
#   Created 9 sep 2017
#   Filename: SwitchHostsInstanceState.ps1
#   
#   Changelog
#   ------------------------------------------------------------------
#   Author              Date            Changes
#   Peter Lykkegaard    14 sep 2017     Added stop/start/status of IIS  
#
#   References
#   http://ittybizzy.blogspot.dk/2013/10/powershell-scripts-to-stopstart-biztalk.html
#   https://social.technet.microsoft.com/wiki/contents/articles/32946.biztalk-server-health-check-powershell-script.aspx
#
#   ------------------------------------------------------------------
param(
    [parameter(ValueFromPipeline)]
    [ValidateNotNullOrEmpty()]
    [string]$handle
    )

# Main routine
function Switch-HostInstanceState
{
  
    Clear-Host 
    
    if (Test-Arguments)
    {
        switch ($handle)
        {
            {$_ -in "Stop", "Start", "Status"} 
            {
                # Disable or Enable all host instances
                # If already disabled receive* hosts will not be enabled
                Invoke-ServiceState $handle

                if ($handle -ne 'Status')
                {
                    # Write current status
                    Invoke-ServiceState "Status"
                }
                break
            }
            default { 
                Show-HelpArguments 
                break
            }            
        }        

    }
}

function Test-Arguments
{
    Write-Host "`n**********************************************************"
    Write-Host ("Handle = '{0}'" -f $handle)

    if (
        $handle.length -eq 0
        ) 
    {
        Write-Host "`nOne or more arguments are missing`n"
        Show-HelpArguments
        return $False
    }
    else
    {
        return $True
    }
    
}

function Show-HelpArguments
{
    Write-Host "**********************************************************"
    Write-Host "Use the SwitchHostsInstanceState.ps1 to `n"
    Write-Host " Needed parameters:"
    Write-Host "   0 : -Handle`tStop|Start|Status"
    Write-Host "`n"
    Write-Host "Usages:  SwitchHostsInstanceState.ps1 -Handle [Switch]"
    Write-Host "Sample:  SwitchHostsInstanceState.ps1 -Handle ""Start"""
    Write-Host "`n**********************************************************`n`n"
    
}

Function Invoke-ServiceState([string] $handle)
{
    # Get all In-process BizTalk hostinstances (HostType=1)
    $inProcessHosts = "HostType=1"          # Exclude IsolatedHosts which does have a corresponding service
    $nsBTS = "root/MicrosoftBizTalkServer"  # Biztalk Namesspace in WMI
    $receiving = "Receiving*"               # All Receiving Hostinstances 

    $filter = "($inProcessHosts)"           # Filter for WMI lookup
    $hostInstances = Get-WmiObject MSBTS_HostInstance -Namespace $nsBTS -Filter $filter 
    $instances = $hostInstances 
    
    switch ($handle)
    {
        "Stop"
        {
            # Disable or Enable all host instances
            # If already disabled receive* hosts will not be enabled
            # Gracefully stop IIS services
            $iis =  Get-WmiObject Win32_Service -Filter "Name = 'W3SVC'"
            if ($iis.State -eq 'Running')
            {
                Write-Host "Stopping IIS Services /noforce..."
                & {iisreset /stop /noforce}
            }

            # Handle all selected host instances
            Write-Host "`nDisable and Stop BizTalk Host Instances "
            Write-Host "**********************************************************"
            break
        }
        "Start"
        {
            Write-Host "`nEnable and Start BizTalk Host Instances "
            Write-Host "**********************************************************"
            # Check for disabled hosts other than receiving, if any found loop through the collection
            $instances = $hostInstances | Where-Object {$_.hostname -notlike $receiving -and $_.IsDisabled -eq $True}
            if (!$instances)
            {
                $instances = $hostInstances
            }
            break
        }
        "Status"
        {
            # Handle all selected host instances
            Write-Host "`nStatus of IIS "
            Write-Host "**********************************************************"
            $iis =  Get-WmiObject Win32_Service -Filter "Name = 'W3SVC'"
            Write-Host ("Web server - {0}" -f $iis.State)

            Write-Host "`nStatus of BizTalk Host Instances "
            Write-Host "**********************************************************"
            break
        }

        default { 
            # Handle undefined or wrong value
            Show-HelpArguments 
            break
        }            
    }

    foreach ($hostInstance in $instances)
    {
        switch ($handle)
        {                           
            "Stop" {    # Disable all but stop only receiving hostinstances

                if (!$hostInstance.IsDisabled)
                {
                    $hostInstance.IsDisabled = $true
                    $hostInstance.Put() > $null

                    Write-Host $hostInstance.hostname 'is disabled'
                }
                if ($hostInstance.hostname -like $receiving)
                {
                    # if service is running
                    if ($hostInstance.servicestate -eq 4)
                    {
                        Write-Host ('Stopping service: {0} ...' -f $hostInstance.hostname)

                        try {
                            $windowsService = ('BTSSvc${0}' -f $hostInstance.HostName)
                            Get-Service -Name $windowsService | Stop-Service
                            #Stop-Service -DisplayName $windowsService
                        }
                        catch {
                            Write-Host ('Error stopping host {0}, please check eventlog for details' -f $hostInstance.hostname), -ForegroundColor "red"
                        } 
                        if ($hostInstance.servicestate -ne 4)
                        {
                            Write-Host ('{0} is stopped' -f $hostInstance.hostname)
                        }
                        
                    }
                }
                break
            }
            "Start" {   # Ensable all but do not start receiving hostinstances
                
                if ($hostInstance.IsDisabled)
                {
                    $hostInstance.IsDisabled = $False
                    $hostInstance.Put() > $null               
                    Write-Host $hostInstance.hostname 'is reenabled'
                }
                if ($hostInstance.hostname -notlike $receiving)
                {
                    # if service is not running try to start it
                    if ($hostInstance.servicestate -ne 4)
                    {
                        Write-Host ('Starting service: {0} ...' -f $hostInstance.hostname)
                        try {
                            $windowsService = ('BTSSvc${0}' -f $hostInstance.HostName)
                            Get-Service -Name $windowsService | Start-Service
                            #Start-Service -DisplayName $hostInstance.HostName
                        }
                        catch {
                            Write-Host ('Error starting host {0}, please check eventlog for details' -f $hostInstance.hostname), -ForegroundColor "red"
                        } 
                        # Notify is started
                        if ($hostInstance.servicestate -eq 4)
                        {
                            Write-Host ('{0} is started' -f $hostInstance.hostname)
                        }
                    }
            }
                break
            }
            "Status" {  # Status for BizTalk Services 
                switch ($hostInstance.servicestate) {
                    1 { $hostInstanceState = "Stopped" }
                    2 { $hostInstanceState = "Start pending" }
                    3 { $hostInstanceState = "Stop pending" }
                    4 { $hostInstanceState = "Running" }
                    5 { $hostInstanceState = "Continue pending" }
                    6 { $hostInstanceState = "Pause pending" }
                    7 { $hostInstanceState = "Paused" }
                    8 { $hostInstanceState = "Unknown" }
                }

                Write-Host $hostInstance.hostname '-' $hostInstanceState
                break
            }
        }
    }

    if ($handle -eq 'Start')
    {
        $iis =  Get-WmiObject Win32_Service -Filter "Name = 'W3SVC'"
        if ($iis.State -ne 'Running')
        {
            # Start IIS services
            Write-Host "`nAttempting to start IIS Services ..."
            & {iisreset /start }        
        }
    }
}

# Entry point
Switch-HostInstanceState

 

Comments are closed