Skip to content

Instantly share code, notes, and snippets.

@otakusid
Last active March 22, 2016 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save otakusid/d621fde09e57bfd2b59f to your computer and use it in GitHub Desktop.
Save otakusid/d621fde09e57bfd2b59f to your computer and use it in GitHub Desktop.
AWS Code Deploy - delete windows service during 'ApplicationStop' event
$serviceName = '[[[service.name]]]' # in format 'Namespace.ServiceName'
$service = Get-WmiObject -Class Win32_Service -Filter "Name='$serviceName'"
$i = $serviceName.LastIndexOf('.');
$serviceShortName = $serviceName.Substring($i + 1);
$eventSourceName = "CodeDeploy.$serviceShortName.ApplicationStop"
if(-Not [System.Diagnostics.EventLog]::SourceExists($eventSourceName)) {
New-EventLog –LogName "Application" –Source $eventSourceName
}
Write-EventLog –LogName Application –Source $eventSourceName –EntryType Information –EventID 1 –Message "script v.: [[[application.version]]]"
if($service) {
$serviceProcessId = $service.ProcessId;
$stopResponce = $service.StopService()
$deleteResponce = $service.delete()
Write-EventLog –LogName Application –Source $eventSourceName –EntryType Information –EventID 1 –Message "Service '$serviceName' marked for deletion"
Write-Host "service '$serviceName' marked for deletion"
Write-EventLog –LogName Application –Source $eventSourceName –EntryType Information –EventID 1 –Message "responces: stop '$stopResponce'; delete '$deleteResponce'"
Write-Host "responces: stop '$stopResponce'; delete '$deleteResponce'"
Write-EventLog –LogName Application –Source $eventSourceName –EntryType Information –EventID 1 –Message "Process with ID '$serviceProcessId' still works. Wait some time"
Write-Host "process with ID '$serviceProcessId' still works. Wait some time"
Wait-Process -Id $serviceProcessId -ErrorAction SilentlyContinue
Write-EventLog –LogName Application –Source $eventSourceName –EntryType Information –EventID 1 –Message "Process with ID '$serviceProcessId' not exist"
Write-Host "process with ID '$serviceProcessId' not exist"
} else {
Write-EventLog –LogName Application –Source $eventSourceName –EntryType Information –EventID 1 –Message "Service '$serviceName' does not exist"
Write-Host "service '$serviceName' does not exist"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment