Somewhere in my script I'm writing a folderstructure to Host with the number of files in each folder [1]:
$FolderName = "BAR"
$ItemCount = "{0:000}" -f 7
Write-Host $ItemCount $FolderName
which would output something like [2]:
007 BAR
044 BAZ
311 FOO
What I actually want is [3]:
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]:
Folder Itemcount
------ ---------
BAR 7
BAZ 44
FOO 311
I would like an output like [5]:
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]?
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)
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.
"$(([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
gci c:\temp *.csv | Select-Object @{Name="Length";Expression={"{0,5}" -f $_.Length}}, Name | Format-Table -AutoSize
$ItemCount=($Count.ToString()).PadLeft(3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With