Last active
March 25, 2020 21:03
-
-
Save cdhunt/79d37a7b64e981d5d0260165dd5c9dac to your computer and use it in GitHub Desktop.
A Linux implementation of Get-Service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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