How to get leading spaces instead of zeros in Powershell?

Question:

Somewhere in my script I’m writing a folderstructure to Host with the number of files in each folder [1]:

which would output something like [2]:

What I actually want is [3]:

I don’t want to use a custom Powershell object because it would output over the full width of the console [4]:

I would like an output like [5]:

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)


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.

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

Source:

How to get leading spaces instead of zeros in Powershell? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply