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
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