I'm really digging all these great opportunities to learn PowerShell. So many resources and lots of super helpful folks to help you on your journey. Signing up to blog about a "Month of Lunches" was a big commitment for me. It helped keep me accountable to spend the time necessary to learn PowerShell. As the end is coming for "Month of Lunches," I have found another opportunity to continue learning PowerShell. The 2012 Scripting Gameshttp://tinyurl.com/c3ru5r2 is about to begin and there is a beginner category. I don't think I'll be winning the competition, but it is another opportunity to keep me moving forward on my PowerShell skills.
Today's lunch is about taking commands and scripts and creating functions. This is great way to create commonly used scenarios in an easy to use/share format.
Don has us work through an example where we take two commands that pull from different outputs and combine the results. This is a great way to learn how to create a function and practice some new techniques. We use the Get-WmiObject Win32_OperatingSystem and Get-WmiObject Win32_LogicalDisk to collect information on computer name, operating system build, service pack and free space on C: drive. You want to break down the tasks so you can identify what are the important parts to the function you are creating.
First step is to create a script that generates the output you want. You then create a function by ‘wrapping' the code into a function. Define the function at the beginning of the script and then call the function at the end of the script file. Once this function is created, you can run the entire script by simply typing in the name of the function. Don recommends keeping the PowerShell norm of Verb-Noun. By adding parameters to the script/function, you can add more flexibility to the function.
The example we were working with in the ‘Month of Lunches' was using Write-Host to produce a text output. To get this to look nice can take some formatting and patience. Don points out that by putting the output into text, you are fighting PowerShell's native capabilities. It's much better to work with objects. PowerShell is much friendlier with objects and you can create a PSObject to hold this these objects. Don gives us two keys to focus on. One, break tasks down into a single function. Two, always have functions return either a single value or output objects that you can pipe to cmdlets like Format, Convert, Sort, etc.
Tomorrow's Lunch is about logic and loops so we will really be tapping some basics of programming. Looking forward to it!
Mar 28 2012, 04:37 PM