less than 1 minute read

I was recently putting some PowerShell scripts together for deployment and maintenance of software to our machine instances. One of the requirements was to be able to discover the service name from a Windows Service executable that uses ServiceInstaller. I needed to be able to extract this value in a generic way in order to query the service and stop it if running. Here is what I was able to put together.

Function Get-WindowsServiceName([string]$exePath)
{
    $assembly = [System.Reflection.Assembly]::LoadFrom($exePath)
    $type = $assembly.GetTypes() | Where { $_.GetCustomAttributes([System.ComponentModel.RunInstallerAttribute], 0).Length -gt 0 } | Select -First 1
    $installer = [System.Configuration.Install.Installer][Activator]::CreateInstance($type)
    $serviceInstaller = [System.ServiceProcess.ServiceInstaller]$installer.Installers[0]
    $serviceInstaller.ServiceName
}

Note that this doesn't support multiple installers in a single executable.

Leave a comment