Why does powershell ignore a `r when followed with 15 `t

Viewed 64

I'm writing a program that outputs a display to the screen containing information on the status of a process running on multiple computers. I've deliberately avoided arrays, objects, and format-table so that I can output each member of the information in a different color based on the status. Example:

Server    Service Status    Latest config backup
------------------------------------------------
Srv01     Running           2021-01-13_1500.bak

The Running will be green, the backup file will be green or red based on the age, etc.

This means a nasty set of:

write-host "`r`t`t`t`t`t`t`t`t`t`t`t`t`t`t`t`t`t`t$servicestatus" -nonewline -foregroundcolor $color

What I've discovered however is that once I hit 15 consecutive `t entries, my powershell window will start to mess up and ignore the initial `r and I end up with text wrapping onto a new line due to reaching maximum screen width.

Server    Service Status    Latest config backup
------------------------------------------------
Srv01     Running           
2021-01-13_1500.bak

examples above exaggerated, length not to scale.

If you can suggest a way to put colors in a format-table, I'll happily switch to an object or array or whatever.

Edit: Please see the below screenshot for illustration. enter image description here

1 Answers

`r (\r in most languages) is the Carriage Return character in PowerShell. To understand what that is you need to know a little bit of history around line endings on different platforms. Once upon a time there were typewriters (yes, the story starts there). The original use of typewriters involved typists both entering a new line AND moving the carriage back to the beginning so that they could start typing at the start of the line. Eventually this became more automated so that typewriters would do both at the click of a button. But enough about typewriters. Some platforms (Windows) kept the history and end their lines with BOTH a new line character (also known as the line feed character) and a carriage return character (the latter representing the physical act of moving the carriage), abbreviated to CRLF; while other platforms (Linux/Mac) dropped the history and kept the only really needed new line character, abbreviate to LF.

So, lines end in either a `r`n or a `n, depending on the platform. However, in PowerShell you can get away with just a `n no matter the platform. The thing is, a `r on its own is ignored, so your code is the same with or without it regardless of the number of tab characters (`t) you use.

For your real issue: PowerShell does automatic line wrapping so either determine the width of things dynamically and pad with spaces to get your alignment or check out PowerShell's builtin custom formatting to see if it would work.

Related