Last active
August 29, 2015 14:25
-
-
Save stuartleeks/d14b045428a633b86d0e to your computer and use it in GitHub Desktop.
PowerShell-friendly docker ps parsing
This file contains 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 PascalName($name){ | |
$parts = $name.Split(" ") | |
for($i = 0 ; $i -lt $parts.Length ; $i++){ | |
$parts[$i] = [char]::ToUpper($parts[$i][0]) + $parts[$i].SubString(1).ToLower(); | |
} | |
$parts -join "" | |
} | |
function GetColumnInfo($headerRow, $propertyNames){ | |
$lastIndex = 0 | |
$lastName = $null | |
$propertyNames | %{ | |
$nextIndex = $headerRow.IndexOf($_, $lastIndex) | |
if ($lastName -ne $null) { | |
New-Object PSObject -Property @{ HeaderName = $lastName; Name = PascalName $lastName; Start=$lastIndex; End=$nextIndex} | |
} | |
$lastIndex = $nextIndex | |
$lastName = $_ | |
} | |
New-Object PSObject -Property @{ HeaderName = $lastName; Name = PascalName $lastName; Start=$lastIndex; End=-1} | |
} | |
function ParseRow($row, $columnInfo) { | |
$values = @{} | |
$columnInfo | % { | |
if ($_.End -lt 0) { | |
$len = $row.Length - $_.Start | |
} else { | |
$len = $_.End - $_.Start | |
} | |
$values[$_.Name] = $row.SubString($_.Start, $len) | |
} | |
New-Object PSObject -Property $values | |
} | |
function ExtractPsInfo(){ | |
begin{ | |
$propertyNames = @('CONTAINER ID', 'IMAGE', 'COMMAND', 'CREATED', 'STATUS', 'PORTS', 'NAMES') | |
$positions = $null; | |
} | |
process { | |
if($positions -eq $null) { | |
# header row => determine column positions | |
$positions = GetColumnInfo -headerRow $_ -propertyNames $propertyNames | |
} else { | |
# data row => output! | |
ParseRow -row $_ -columnInfo $positions | |
} | |
} | |
end { | |
} | |
} | |
## TODO - move to generic version | |
#function DockerParse($propertyNames){ | |
# | |
# begin{ | |
# $positions = $null; | |
# } | |
# process { | |
# if($positions -eq $null) { | |
# # header row => determine column positions | |
# $positions = GetColumnInfo -headerRow $_ -propertyNames $propertyNames | |
# } else { | |
# # data row => output! | |
# ParseRow -row $_ -columnInfo $positions | |
# } | |
# } | |
# end { | |
# } | |
#} | |
# e.g. : | |
# docker --tls ps -a --no-trunc | ExtractPsInfo | ft |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment