Skip to content

Instantly share code, notes, and snippets.

@cdhunt
Last active March 25, 2020 21:03
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 cdhunt/79d37a7b64e981d5d0260165dd5c9dac to your computer and use it in GitHub Desktop.
Save cdhunt/79d37a7b64e981d5d0260165dd5c9dac to your computer and use it in GitHub Desktop.
A Linux implementation of Get-Service
Function Get-Service {
[CmdletBinding()]
Param(
[Parameter( Position = 0, ValueFromPipeline = $True )][String]$Name
)
Begin {
# Stop Function if Not Linux
If ( -Not $IsLinux ) {
Throw "This function should only be run on Linux systems"
}
}
Process {
If ( (Get-Process -Id 1).ProcessName -eq 'systemd') {
If ( $PSBoundParameters.ContainsKey('Name') ) {
$services = & systemctl list-units "$Name.service" --type=service --no-legend --all --no-pager
} Else {
$services = & systemctl list-units --type=service --no-legend --all --no-pager
}
$services | ForEach-Object {
$service = $_ -Split '\s+'
$name, $load, $active, $sub, $desc = $service
[PSCustomObject]@{
"Name" = $name.Split('.') | Select-Object -First 1
"Load" = $load
"Active" = $active
"State" = $sub
"Description" = $desc -join " "
}
}
} Else {
$services = & service --status-all *>&1
$services | ForEach-Object {
$service = $_.ToString()
$status = switch ($service[3]) {
'-' {"Stopped"}
'+' {"Running"}
'?' {"Unavailable"}
default {"Unavailable"}
}
$name = ($service -split " ")[5]
[PSCustomObject]@{
"Name" = $name
"State" = $status
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment