ps/Modules/Alkami.PowerShell.Services/Public/Get-ServiceByChocoName.ps1
2023-05-30 22:51:22 -07:00

53 lines
2.3 KiB
PowerShell

function Get-ServiceByChocoName {
<#
.SYNOPSIS
Returns a service instance by a chocolatey package name.
.PARAMETER ChocolateyName
Chocolatey Package name to search for
.PARAMETER IncludeDisabled
Include services with StartMode set to Disabled
#>
Param(
[Parameter(Mandatory=$true)]
[string]$ChocolateyName,
[Parameter(Mandatory=$false)]
[switch]$IncludeDisabled
)
$logLead = Get-LogLeadName
Write-Verbose "$logLead : Searching for chocolatey service $ChocolateyName"
# This lookup takes 1ms to perform, the below lookup takes ~400ms to perform.
$existingService = Get-Service -Name $ChocolateyName -ErrorAction SilentlyContinue
if ($null -ne $existingService) {
if ($existingService.StartType -eq 'Disabled' -and -not $IncludeDisabled) {
Write-Warning "$logLead : Chocolatey service $ChocolateyName was found, but is disabled. Returning $null"
return $null
}
# match the prior output with what we have here
# Most callers only want the name. Set- MicroserviceConfigurationBasedState wants the other fields.
return @{
Name = $existingService.Name
StartMode = $existingService.StartType
State = $existingService.Status
}
}
$chocolateyInstallPath = Get-ChocolateyInstallPath
$chocolateyLibPath = Join-Path -Path $chocolateyInstallPath -ChildPath "lib"
$chocolateyServicePath = Join-Path -Path $chocolateyLibPath -ChildPath $ChocolateyName
# Trailing backslash to prevent matching a substring of a packagename like alkami.ms.parent matching alkami.ms.parent.child
$chocolateyServicePathString = "$chocolateyServicePath\"
$servicePath = $chocolateyServicePathString.Replace("\", "\\")
# TODO: Should this use Get-ServiceInfoByCIMFragment to consolidate usages of Get-CIMInstance Win32_Service since it already matches on path for this scenario? -- cbrand ~ 2022/06/22
# The above lookup takes about 1ms, this one takes about 400ms
$service = Get-CIMInstance win32_service | Where-Object { ($_.PathName -match $servicePath) -and ($IncludeDisabled.isPresent -or ($_.StartMode -ne "Disabled"))} | Select-Object -First 1
if (!$service) {
Write-Warning "$logLead : Chocolatey service $ChocolateyName could not be found!"
return $null
}
return $service
}