How can I indent output from the Format-Table cmdlet to a specific column?
I have:
> $SomeValues | Format-Table -HideTableHeaders
A 1
B 2
C 3
But I'd like:
A 1
B 2
C 3
How can I indent output from the Format-Table cmdlet to a specific column?
I have:
> $SomeValues | Format-Table -HideTableHeaders
A 1
B 2
C 3
But I'd like:
A 1
B 2
C 3
Thanks everyone for your answers. They helped me figure out how to do what I wanted using calculated properties. The Expression must be one less than the amount of indent, due to the automatic single character space between columns in the table.
If you're using the -AutoSize flag:
Write-Host "Not indented"
Write-Host " Indented"
$a = @{ Aa = 1; Bbb = 2; Cccc = 300}
$a | Format-Table -Property @{Expression=" "},Name,Value -AutoSize -HideTableHeaders
If you're not using the -AutoSize flag:
Write-Host "Not indented"
Write-Host " Indented"
$a = @{ Aa = 1; Bbb = 2; Cccc = 300}
$a | Format-Table -Property @{Expression={}; Width=3},Name,Value -HideTableHeaders
The output looks like:
Not indented
Indented
Bbb 2
Aa 1
Cccc 300
There's another way that doesn't require creating an additional column. You can simply take the normal output from the Format-Table command, use Out-String to convert it to a string array, and then use ForEach-Object to print out each string with padding. Here's an example using Get-Process.
$indent = " "
(Get-Process svchost) | Format-Table -Property Id, ProcessName | Out-String -Stream | ForEach-Object {Write-Output "$indent$_"}
Use:
PS> $a = @{A=1; B=2; C=3}
PS> $a.GetEnumerator() | %{ "{0,10}{1,5}" -f $_.key, $_.value }
A 1
B 2
C 3
This should do it
function Indent-ConsoleOutput($output, $indent=4){
if(!($output -eq $null)){
if(!( $indent -is [string])){
$indent = ''.PadRight($indent)
}
$width = (Get-Host).UI.RawUI.BufferSize.Width - $indent.length
($output| out-string).trim().replace( "`r", "").split("`n").trimend()| %{
for($i=0; $i -le $_.length; $i+=$width){
if(($i+$width) -le $_.length){
"$indent"+$_.substring($i, $width)
}else{
"$indent"+$_.substring($i, $_.length - $i)
}
}
}
}
}
'## Get-Process'
Indent-ConsoleOutput ((get-process)[0..5]|format-table) 4
''
'## Log Stye Output'
Indent-ConsoleOutput ((get-process)[0..5]|format-table) " $(Get-Date) "
For a generic solution
function Indent-ConsoleOutput($output, $indent=4){
if(!($output -eq $null)){
if(!( $indent -is [string])){
$indent = ''.PadRight($indent)
}
$width = (Get-Host).UI.RawUI.BufferSize.Width - $indent.length
($output| out-string).trim().replace( "`r", "").split("`n").trimend()| %{
for($i=0; $i -le $_.length; $i+=$width){
if(($i+$width) -le $_.length){
"$indent"+$_.substring($i, $width)
}else{
"$indent"+$_.substring($i, $_.length - $i)
}
}
}
}
}
'## Get-Process'
Indent-ConsoleOutput ((get-process)[0..5]|format-table) 4
''
'## Log Stye Output'
Indent-ConsoleOutput ((get-process)[0..5]|format-table) " $(Get-Date) "
Use:
$SomeValues | Format-Table -HideTableHeaders -AutoSize