Question:
Somewhere in my script I’m writing a folderstructure to Host with the number of files in each folder [1]:
1 2 3 4 5 |
$FolderName = "BAR" $ItemCount = "{0:000}" -f 7 Write-Host $ItemCount $FolderName |
which would output something like [2]:
1 2 3 4 |
007 BAR 044 BAZ 311 FOO |
What I actually want is [3]:
1 2 3 4 |
7 BAR 44 BAZ 311 FOO |
I don’t want to use a custom Powershell object because it would output over the full width of the console [4]:
1 2 3 4 5 6 |
Folder Itemcount ------ --------- BAR 7 BAZ 44 FOO 311 |
I would like an output like [5]:
1 2 3 4 5 6 |
Folder ItemCount ------ --------- BAR 7 BAZ 44 FOO 311 |
So close together which makes it much more readable. But I chose my solution (ItemCount in from of FolderName) as a second best option because I could not get this to work.
How can I get an output like in [3] or [5]?
Answer:
So a couple of ways to go about this. Depends on what you are doing with the end result. Uses the alignment option of the -Format
parameter (5 places)
1 2 3 4 |
gci c:\temp *.csv | ForEach-Object{ "{0,5} {1}" -f $_.Length, $_.Name } |
Or maybe the string method
.PadLeft()
. Both examples that following should produce the same output. Readability could be impacted in the first. Note that .PadLeft()
is a string method. In my examples I am using length
which is int
so we have to cast to string.
1 2 3 |
"$(([string]($_.Length)).PadLeft(5)) $($_.Name)" "{0} {1}" -f ([string]($_.Length)).PadLeft(5),$_.Name |
Now… perhaps you just was to work with
Format-Table
for nice on screen output. Just need to use my first example in another way
1 2 |
gci c:\temp *.csv | Select-Object @{Name="Length";Expression={"{0,5}" -f $_.Length}}, Name | Format-Table -AutoSize |