Skip to content

Instantly share code, notes, and snippets.

@drlsdee
Created February 13, 2024 07:10
Show Gist options
  • Save drlsdee/877655359eba9ec0ea7b4ca7963fb2de to your computer and use it in GitHub Desktop.
Save drlsdee/877655359eba9ec0ea7b4ca7963fb2de to your computer and use it in GitHub Desktop.
Get-Win32Service - returns an instance of class Win32_Service including the image path with command line arguments and the service account name
function Get-Win32Service {
[CmdletBinding()]
param (
[Parameter(Mandatory,Position=0)]
[Alias('n')]
[string]
$Name,
[Parameter(Position=1)]
[ValidateSet('Name','Status','ExitCode','DesktopInteract','ErrorControl','PathName',
'ServiceType','StartMode','Caption','Description','InstallDate','CreationClassName',
'Started','SystemCreationClassName','SystemName','AcceptPause','AcceptStop','DisplayName',
'ServiceSpecificExitCode','StartName','State','TagId','CheckPoint','DelayedAutoStart','ProcessId','WaitHint')]
[Alias('Properties', 'p')]
[string[]]$Property = ('ProcessId','Name','StartMode','State','Status','ExitCode','StartName','PathName'),
[Parameter(Position=2,ValueFromPipeline)]
[Alias('cn')]
[string]$ComputerName
)
begin {
#region DeclareMessages
[string]$myName = '[{0}]:' -f $MyInvocation.InvocationName
[string]$msgError = '{0} The operation "{1}"; the object: "{2}"; exception: "{3}"; message: "{4}"; inner exception: "{5}"'
# $msgError -f $myName, $operationName, $objectName, $_.Exception.GetType().FullName, $_.Exception.Message, $_.Exception.InnerException
#endregion DeclareMessages
# Query
[string]$wmiQuery = [string]::Format(
'SELECT {0} FROM Win32_Service WHERE Name = "{1}"',
[string]::Join(
',', $Property
),
$Name
)
}
process {
$splatGwmi = @{
Query = $wmiQuery
ErrorAction = [System.Management.Automation.ActionPreference]::Stop
}
if (-not [string]::IsNullOrEmpty($ComputerName)) {
$splatGwmi.Add('ComputerName', $ComputerName)
}
try {
[wmi]$wmiObject = Get-WmiObject @splatGwmi
}
catch {
[string]$msgErrGwmi = $msgError -f $myName, 'Get-WmiObject', $wmiQuery, $_.Exception.GetType().FullName, $_.Exception.Message, $_.Exception.InnerException
Write-Warning -Message $msgErrGwmi
$wmiObject = $null
}
if ($null -eq $wmiObject) { return }
return $wmiObject
}
end {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment