image-3.

#PowershellBasics: Writing to the screen

,

Writing to the screen is a really basic debugging technique. That said, since I’m really new with Powershell this is something I needed to get good at quickly. There are two commands that I’m making use of. The first is Write-Host. This is similar to Print in SQL Server. Print is pretty basic and your only option is to pass in what you want printed, and it’s going to go on it’s own line. Write-Host on the other hand has a number of additional flags that you can use. A few of my favorites are -nonewline, -foregroundcolor, and -backgroundcolor.

By default, Write-Host, much like Print, writes it’s output and then adds a new line afterwards. -nonewline let’s you bypass that.

$var = 4
Write-Host "Var is: " -nonewline
Write-Host $Var
This is great but can be kind of hard to see when you’ve tested something several times, and it prints out dozens of lines of code and/or debugging information. So the next thing I do is use the Clear-Host command, which can also be abbreviated as CLS. If you are old enough you’ll remember CLS from the DOS days where it stood for clear screen. I’ve gotten into the habit of adding it to the top of my code so that it clears the host (the output screen) before my code runs. I’m not going to bother to demonstrate because it’s really pretty basic.

Last but by no means least –foregroundcolor, and -backgroundcolor. If I’m generating a lot of output and throwing a debug in the middle, it can take a bit to find the information I’m looking for. By changing the background and/or foreground (the text itself) colors I can make it far easier to see. If you were wondering why I split the write for the description and the variable itself, it’s so I could do two different colors for the text. There might still be a way to do this in a single line but I don’t know it and I find this fairly easy to follow so I’ll stick with it for now.

Clear-Host
$var = 4
Write-Host "Var is: " -nonewline -foregroundcolor black -backgroundcolor red
Write-Host $Var -BackgroundColor red

Original post (opens in new tab)
View comments in original post (opens in new tab)

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating