Guy’s Scripting Ezine 126 – PowerShell Cmdlet Scripts

Guy’s Scripting Ezine 126 – PowerShell Cmdlet Scripts

 ♣

This Week’s Secret

I declare a bias in that PowerShell suits my learning style.  What I like is that understanding the verb-noun construction is easy.  Cmdlets are short.  If I copy and paste someone else’s script I can actually grasp what every word means.  When I get stuck, PowerShell’s built-in help is waiting in the wings and talks to me like a human being and not like a geek.

7 Things to get started with PowerShell

  1. Where to Download (Get OS specific version)
  2. Begin with old dos commands (dir, CD, Ping)
  3. Look for the Verb-noun Pair (Set-ExecutionPolicy)
  4. Call for help (get-help wmiobject)
  5. Create Scripts (Cmdlets)
  6. Deploy Pipe symbol | (Join commands | filter)
  7. Master $_.  It means the current object in the pipeline. (Where {$_.name -contains "Microsoft})

Inch by inch and PowerShell will be a cinch.  No other scripting language is so easy for the newbie, yet offers so much sophistication for the expert.  One reason that you can start learning NOW is you can still use all your old commands such as cd, dir and even Ipconfig.  My vision is that little by little, you can progress from commands you already know to PowerShell’s get-object or set-property commands.

Now I don’t want to pretend that it’s easy to become an expert at PowerShell, merely to emphasise that it’s easy to get going.  While anyone can hit a golf ball around a putting green, only experts can hit the ball straight with a driver.  Most people can get the ball airborne with a sand wedge, but only a professional can hit a ball out of the rough, clear a water hazard, then hold the ball on a down-slope with backspin.  PowerShell is like golf in that anyone can play, but few will have the effortless control of a professional.  To stretch the analogy to the limit, just as we can play along with our favourite players from the comfort of our arm-chairs, so we can emulate PowerShell experts by copying and pasting their code.

To let you into a secret, it takes me far too long to fine-tune the simple cmdlets that I present on this and other pages.  However, with time and patience I always believe that I can achieve my scripting goals.  My biggest problem is getting distracted. Adjusting one tiny piece of formatting lures me to playing with a whole array of commands (format-list, format-table -autosize – wrap).  On another occasion, I just wanted to use the * wild card, but I got lured into experimenting with -like, and -contains.

Solarwinds Config GeneratorGuy Recommends: The Free Config Generator

SolarWinds’ Config Generator is a free tool, which puts you in charge of controlling changes to network routers and other SNMP devices.  Boost your network performance by activating network device features you’ve already paid for.

Guy says that for newbies the biggest benefit of this free tool is that it will provide the impetus for you to learn more about configuring the SNMP service with its ‘Traps’ and ‘Communities’. Try Config Generator now – it’s free!

Download your free copy of Config Generator

PowerShell now in RC2 (Release Candidate Two)

I don’t know whether to laugh or cry, because last week Microsoft released RC2 (Release Candidate) for PowerShell.  If you get involved with Microsoft’s beta software you have to face a constant stream of new versions; naturally it’s up to you if you want to make each upgrade, or whether to skip a few.

From the point of view of learning the basics, any version of PowerShell (Monad) will do.  The problem is that each beta version brings subtle changes, as a result, some previous settings don’t work.  For example the file extension for cmdlet scripts in PowerShell (RC1 and RC2) is .ps1, whereas in Monad (Beta 1) it was .msh.  Also the default path for profile.ps1 is now %UserProfile%\My Documents\WindowsPowerShell\profile.ps1.  I emphasise that the folder for profile.ps1 is called: WindowsPowerShell in RC2, not PSConfiguration as in RC1.

This Week’s Mission

This week I am very much in ‘Getting you started’ mode, specifically I want to show you how to create PowerShell scripts or cmdlets.  In my opinion, if you master cmdlet scripts, and they are not hard, then you will go on to become a great PowerShell script writer.  If you don’t use cmdlets, then you will be forever merely tinkering with one-off lines of code.  Cmdlet is just a fancy, precise or technical name for a script file with .ps1 extension.  Whereas VBScript stores lines of code in .vbs files, PowerShell uses .ps1 and calls them cmdlets or plain scripts.

My overall strategy is to provide two routes to get you started with cmdlets or scripts.  Route A is designed simply to demonstrate the 3 steps of the cmdlet technique.  Route B is a huge leap in complexity but it is a ‘real world’ example.

My mission is divided into three parts.

a) To persuade you to alter your settings and thus allow scripts to run in your PowerShell box.
b) To save the lines of code as text files with .ps1 file extension.
c) Finally learning the knack of how to call your text file (cmdlet) from the PowerShell command line.

Mastering cmdlets has two hidden benefits, they document what you do and they provide a record of your achievements.

Guy Recommends: Tools4ever’s UMRAUMRA The User Management Resource Administrator

Tired of writing scripts? The User Management Resource Administrator solution by Tools4ever offers an alternative to time-consuming manual processes.

It features 100% auto provisioning, Helpdesk Delegation, Connectors to more than 130 systems/applications, Workflow Management, Self Service and many other benefits. Click on the link for more information onUMRA.

Route A – Simple Technique

Prerequisites

  1. Download PowerShell RC2 from Microsoft’s site, there are separate versions for each operating system, for example XP and Windows Server 2003.
  2. Optionally, seek out Microsoft’s 32 page Getting Started Guide.  Curiously, it installs in the Windows\System32\WindowsPowerShell\v1.0\ folder.
  3. Make judicious use of the get-help built-in cmdlet, for example get-help get-ExecutionPolicy.  Or plain help get-ExecutionPolicy

Mission 1 – Allow your computer to run PowerShell cmdlet scripts with remotesigned

The secret of allowing your PowerShell scripts to run is the noun ExecutionPolicy. To investigate the options try:
get-ExecutionPolicy -?

Crucial Command
set-ExecutionPolicy remotesigned

Now check with

get-ExecutionPolicy
Expected Response: remotesigned

See more about the PowerShell set-ExecutionPolicy command

Mission 2 – Create a very simple .ps1 cmdlet

At the risk of repeating myself – again, WMI is the killer reason to learn PowerShell in the autumn of 2006.  Long term we are all learning PowerShell because it’s essential for Exchange 2003 administration, and because PowerShell will be the scripting language of the future.  Meanwhile I want emphasise that you can do other useful stuff with PowerShell.  For starters, you can use familiar commands such as cd, or even ping, at the PowerShell command line.  If you want to be an expert at PowerShell then abandon cmd and use PowerShell for every day tasks.  Slowly extend your capabilities by trying new PowerShell commands, soon you will be hooked on this new scripting language.

Goal – Create our first .ps1 file

By using the very basic command, Ping localhost troubleshooting will be easier. My point is that if it does not work, then we can rule out an syntax error in the script.

Pre-requisites

Know the IP addresses of machines on your subnet.

Decide where to keep your scripts, for example, c: \scripts.

Ping localhost

Instructions. 

This really is easy.  Let us get success and then build on the feel-good factor.  (More complex examples in Route B.)

  1. Open Notepad
  2. Type:
  3. Ping localhost
  4. File (Menu) Save As c: \scripts\myping.ps1

Mission 3 – Call our .ps1 cmdlet

This is straightforward.  Just launch the PowerShell program and in the command box, type the path to the file.  Even better, navigate to the folder where you store your scripts (cd c: \scripts) then just type dot slash and the filename .\myping   There is no need to type the .ps1 extension.

Method one.  At the PowerShell command line type:
c: \scripts\myping

Method two. With the prompt at c: \scripts >
.\myping

Route B – A more complex ‘real world’ example

As I mentioned earlier, WMI scripts are the killer reason for learning PowerShell. Therefore, let us create a script (cmdlet) which investigates possible wmiobjects.

cls
wmiobject -list | where {$_.name -like "win32_p*"}

To save your script, copy the above commands into notepad, add a .ps1 extension, for example, w32.ps1.  Make sure it’s not w32.ps1.txt.  I am assuming you save to c :\scripts.

Execute your script: Method one.  At the PowerShell command line type:
c: \scripts\w32

Execute your script:  Method two.  Navigate to the c: \scripts folder type:
.\w32

Note 1: You can make the script both simpler and more general by trying:
wmiobject -list

Note 2: Observe Win32_PingStatus among the WMI objects, because we are going to use this class in the more advanced script.

Guy Recommends: SolarWinds Free Network Bandwidth MonitorFree Real-Time Bandwidth Monitor

This freeware monitor is great for checking whether your network’s load-balancing is performing as expected, for example, are two interfaces are getting about equal traffic?

It’s easy to install and straightforward to configure. You will soon be running tests to see how much network bandwidth your applications consume.

The GUI has a lovely balance between immediate network traffic data in the middle, combined with buttons to seek related data and configuration settings. Give this monitor a try, it’s free! 

Download your free network bandwidth monitor

If you need more comprehensive network analysis software:
Download a free trial of NPM (Network Performance Monitor)

Satisfyingly Tough Route B

Here is a real task to discover which IP addresses are in use on your local subnet mask. The tactic is to loop through all the possible IP addresses on your local network.

Pre-requisites

1) Write down the IP address of your local network, this should be just the first 3 octets, for example 10.1.0  or 192.168.1. (Not 10.1.0.20 as that’s 4 octets)

2) Check the very start of the script 20..65| ForEach-Object.  20 is the IP address of the first host we are going to check and 65 the last.  Please adjust these figures for your network.  1..254 is the safest, but you may get bored waiting for the script to complete.  Best to amend to create a suitable range for your subnet.

3) Be aware that StatusCode = 0 means a successful ping.

Instructions:

Copy these commands into notepad, save with a .ps1 extension. For example pings.ps1
Execute the script from the PowerShell command line. For example: .\pings

20..65 | `
ForEach -Process {WmiObject -Class Win32_PingStatus -Filter ("Address=’192.168.1." + $_ + "’") `
-ComputerName .} | Select-Object -Property Address, StatusCode

Troubleshooting

Read any error messages.  Read the error message again, believe that PowerShell is a good communicator. 

Have you run this command: set-ExecutionPolicy remotesigned

The most likely error is caused by extra carriage return placed in your script by the ezine.  If you have notepad make sure that there are no hard carriage returns between the first and second lines.

Try copying and pasting the above cmdlet code directly into the PowerShell interface.

If the script continues to fail, go back and try a simpler script.  Build on success.

Notes: Where to start!

Note 1: As promised, this script employs Win32_PingStatus

Note 2: Trace how PowerShell executes the ForEach loops and cycles thought the IP Addresses.  It starts at 192.168.1 (+20) and carries on looping up to 192.168.1.65.

Note 3: One construction to learn is $_ which means this pipeline.

Get your copy of PowerShell free from Microsoft

Guy’s Challenges – Put these in Cmdlets

Challenge 1: wmiobject -list | where {$_.name -like "win32_n*"}

Challenge 2: Try help select-object

Challenge 3:  Experiment with the appending the pipe symbol to your cmdlets for example:
wmiobject win32_ntdomain
wmiobject win32_ntdomain |select-object -property name, description, domaincontrolleraddress

Summary of PowerShell Cmdlets

Some people call them cmdlets, others call them PowerShell scripts.  The secret of learning about PowerShell, is to master the three steps needed to create then executing multiple lines of code stored in a text file.  What this cmdlet technique will do for you is help you tackle more complex code, keep a record of what you have done and most importantly, transform you from a dabbler to a serious player.

If you like this page then please share it with your friends

 


See more Microsoft PowerShell v 3.0

PowerShell 3.0  • What’s New in PowerShell 3.0  • PowerShell 3.0 Foreach-Object

PowerShell Show-Command  • Out-GridView -PassThru  • PowerShell Ordered Hash Tables

PowerShell Home  • PowerShell 3.0 Get-ChildItem  • PowerShell 3 -NotIn  • PowerShell 3.0 Where