Scripting Games 2011 Beginner Event 5 Commentary

My commentary for Beginner Event 5 in the 2011 Scripting Games is now available. One item that seems to be missing on the ScriptingGuys site is my complete solution so I thought I would share it here, plus a variation.

My sample solution is perhaps a little over-wrought for a beginner level script, but I wanted to demonstrate what I felt were some inportant scripting techiniques.
[cc lang=”PowerShell”]
#Requires -version 2.0

#You need to collect the user name, computer name, domain name, and the operating system information
#from a number of computers. To make matters easier, you have decided to write the information to a
#text file. The text file needs to be saved as an ASCII file, and not as Unicode. You should include
#the date in which the information was gathered to determine reliability of the information.

#Design points
# Extra points for a script that will work against a remote machine
# Extra points for a script that will accept a Text file, CSV or other type of input of remote computer names
# Extra points for adding useful help information and comments
# Design points for clear easy to read code, and use of native Windows PowerShell cmdlets

#write the computername to the console as a status message
Write-Host $Computer.toUpper() -ForegroundColor Cyan

#ping the computer using Test-Connection. I’m saving the results to a variable
#so that I can get the IP address. I set the ErrorAction preference to SilentlyContinue
#to suppress error messages
$ping=Test-Connection -ComputerName $Computer -Count 2 -ErrorAction “SilentlyContinue”
if ($ping)
{
#if the computer is pingable get WMI information
Try
{
#attempt to retrieve WMI information and if there is an error catch it
$OperatingSystem=Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer -ErrorAction Stop
$ComputerSystem=Get-WmiObject -Class Win32_ComputerSystem -ComputerName $Computer -ErrorAction Stop

#write a progress message on the console if a file path was specified
#otherwise nothing is displayed which for a long running command migh
#lead the user to think something is wrong. When a file is not used each
#computer is written to the console
if ($Filepath)
{
Write-Host $Computer.toUpper() -ForegroundColor Cyan
}

if ($FilePath)
{
#add the object to the data array in case we want to save it to a file
$data+=$object
}
else
{
#Otherwise write the new object to the pipeline
Write-Output $object
}

}
else
{
#display a warning if the WMI information is not present. This should never really
#be reached.
Write-Warning “There was an unknown problem. Not all information was available.”
}
} #close Try scriptblock