Monday, April 2, 2012

Month of Lunches - Day 16


Day 16 - Input and Output

Today's lesson delves a little deeper into the how to get the most out of your information in PowerShell. It's all about input and output.

First up is Read-Host. This is used to prompt and collect input during a command or script and can be very useful. These inputs are done at the Shell prompt except for in the ISE, which is done in a GUI box. For example try this:

                Read-Host "Enter a computer name"

On the following line you will be Prompted with "Enter a computer name". Pretty cool. Place it in a variable ($PC = Read-Host "Enter a computer name") in a script that runs in the ISE and you will be prompted every time you run the scripts. Always want it to prompt you with a GUI box! Dons got you covered. It gets a lot trickier, and this is a two parter. The first part calls the portions of the .NET Framework required to make the box and loads it. The second part is actually the creation of the GUI input box from that .NET framework piece.

                [void][system.reflection.assembly]""LoadWithPartialName('Microsoft.VisualBasic')
                $computername = [microsoft.visualbasic.interaction]::inputbox('Enter a Computer Name','Computer Name','localhost')

In the second command you will notice the three parameters (Name, Computer Name, and Localhost). These can all be changed. The first is the Text of the prompt itself. Second is the title of the GUI box. Third is the default value you want to be in the input box (you can leave this parameter blank if you like).

The next cmdlet we covered is Write-Host. You can pretty much guess what this one does by the name. It writes data and values to the hosts screen. The cool thing about the cmdlet is its ability to change forground (text) and background colors of the output. For instance:

                Write-Host "STOP" -Foreground Black -background red

The Last major cmdlet we covered here was Write-Output. This command as it turns out is one of PowerShells default cmdlets that gets processed behind the scenes. This command as well as the previous command puts the input into the pipeline. Write-Output however does not allow formatting of text like Write-Host.


No comments:

Post a Comment