With PowerShell
you have a choice, you can either type commands directly at the shell's command line, or else
you can store the same commands in a text file. Naturally, you then call that script file, known as a cmdlet, from
the
PowerShell command line.
As with other script languages, notepad is an adequate vehicle for writing or editing scripts, the only PowerShell specific requirement is that you must save the
cmdlet with a .ps1 file extension. (Note this differs from
the Monad Beta
where the extension was .msh). Writing scripts has two extra benefits, it documents your commands,
so that you don't forget them, and also, these cmdlet files provide a record of your PowerShell achievements.
First Meaning of
PowerShell Cmdlet
Cmdlet has two meanings in Windows PowerShell; the first meaning of cmdlet is a synonym
for a PowerShell script. A PowerShell cmdlet is a series of commands, usually more than one line, stored in a text file with a .ps1 extension. It
is this scriplet meaning of cmdlet that I feature on this page.
Second Meaning of
PowerShell Cmdlet In PowerShell circles there appears to be a second meaning
for the word cmdlet. For example Microsoft say,
cmdlet means a built-in PowerShell command, which corresponds to a single verb-noun pair. Such a cmdlet is often accompanied by an alias, for example:
get-Member with its alias of gm.
Advantages of Cmdlets Once you have experimented with a few basic instructions at the PowerShell command line, you may wish to store your code in its own cmdlet
file.
The benefit is that you can replay these perfect lines of instructions later. This strategy becomes more
and more useful as the code grow in complexity. My tactic is once a cmdlet achieves my basic objective, I
call for 'SaveAs', and then use the copy for further development. Seven times out of ten the 'development' goes hopelessly wrong, at which point I am so grateful that I saved a working copy.
I hope that you are getting the idea of a cmdlet. Spend time perfecting the PowerShell commands, then save them in a text file.
This technique saves you typing in lines of code and the command line, instead, you call
the cmdlet by typing: dot slash and followed by its filename, for example .\memory.
Incidentally, building PowerShell cmdlets fits in with my strategy of assembling
scripts in sections.
PowerShell Cmdlets
- Three Quick Instructions
Creating these Windows PowerShell cmdlets is
straightforward, and most rewarding. Here are three essential tasks to ensure that the instructions in these script files execute correctly.
For security, the operating system won't run PowerShell scripts by default. Thus we need to adjust the
ExecutionPolicy to allow PowerShell scripts to run. The better method is to issue this instruction at the PowerShell command line: set-ExecutionPolicy RemoteSigned. Alternatively you could
edit the registry.
Make sure that you save the filename with a .ps1 extension.
Learn the knack of calling the file from the PowerShell command line, either by typing the full path: D: \scripts\filename, or if you were already in the D: \scripts folder, just type: .\filename (note
the rhythm: dot slash filename).
Note 1: Let me explain, this is how I like to call cmdlets from a subdirectory. D: \scripts is my main script directory, however, I create cmdlets in subdirectories such as: D:
scripts\wmi\32proc.ps1 . Assuming that I am at the PowerShell command line in the D: \scripts folder, all that I type at the prompt is: .\wmi\32proc. .
Note 2: It took me ages to deduce that all I needed was plain .\filename. Avoid over-think, when you call the cmdlet file you
don't need to add the extension. Adding .ps1 is not necessary .\filename will suffice.
Note 3: While this dot slash (.\) method of executing the cmdlet script seems cumbersome, Microsoft decided on this method for security reasons. Hackers, phishers and the like could trick
people into executing a rogue PowerShell script by clicking on it. However, nothing happens - unless you proceed the script with .\ this safety feature offers a measure of protection from such mischief
makers.
Guy Recommends: SolarWinds Engineer's Toolset v10
The Engineer's Toolset v10 provides a
comprehensive console of utilities for troubleshooting computer problems. Guy says
it helps me monitor what's occurring on the network, and the tools
teaches me more about how the system literally operates.
There are so many good gadgets, it's like having free rein of a
sweetshop. Thankfully the utilities are displayed logically: monitoring, discovery, diagnostic, and Cisco tools.
Download your copy of the Engineer's Toolset v 10
The following instructions are the same as those above, but with extra step-by-step directions.
1a) PowerShell's
ExecutionPolicy command
I prefer this method, which
employs PowerShell's own commands to control the script Execution Policy. At the PS prompt type:
# PowerShell set-ExecutionPolicy
get-ExecutionPolicy # Now try: set-ExecutionPolicy -? # Here is the crucial command: set-ExecutionPolicy RemoteSigned
N.B. get-ExecutionPolicy is available in PowerShell but not
in the Monad beta.
1b) PowerShell Registry Adjustment
For security, and by default, Microsoft prevent PowerShell from executing cmdlet scripts;
consequently we need to change a specific registry setting to allow our cmdlets to execute. If you
don't make my amendment you may get the following error message when you call for a cmdlet script. 'The execution of scripts is disabled on this system'.
Our task is to open the registry and amend the value of the REG_SZ
ExecutionPolicy, specifically change Restricted to RemoteSigned. There
are two additional values called Unrestricted and AllSigned. However, RemoteSigned is the best because it allows you to run scripts locally,
while preventing people from hacking you from
other machines e.g. the internet. To check the setting launch regedit and navigate to:
(In some versions of
PowerShell / Monad the path
maybe slightly different. HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.Management.Automation.ps1)
Change this registry key: REG_SZ
ExecutionPolicy
RemoteSigned.
When you create your PowerShell cmdlet with notepad, the filename must have a .ps1 extension for example, RunningProcess.ps1. One way of creating such a file is to save your PowerShell
commands in notepad, then from the file menu: Save As, Type, All Files, RunningProcess.ps1. Just to
be doubly sure, you could put the filename in double quotes, for example: "RunningProcess.ps1". I maybe paranoid, but please check the file is not called RunningProcess.txt or RunningProcess.ps1.txt.
What you put in filename.ps1
are the same commands that you type in the PowerShell box. You could start
by creating a file with a simple verb-noun
pair, for example just: get-Process.
This may seem too simple, but my philosophy is keep things straightforward and build on success.
Here is a more advanced set of instructions just to give you the idea of the power of the cmdlets.
# RunningServices.ps1 PowerShell Cmdlet # This script generates a report about Running Services # Guy Thomas September 2007 # Version 1.5
"" # Insert a blank line
"Report generated at " + (get-date) ""
# Insert blank line
"Services that are running" get-service | where-object { $_.status -eq "Running"}
Learning Points
Note 1: The key command in this example is: get-service. Observe the singular noun service, furthermore, PowerShell specializes in consistency, thus nouns are always
singular.
Note 2: Let us dissect the where clause. {$_, is a special variable to indicate, in the current pipeline. The dollar sign indicates
we are using a variable and the underscore has the special
meaning, a value in this stream. The process object has many properties, amongst them is .status. -eq means the left side equals the right side value.
Observe the cmdlet and see that in this instance, we are looking for a
value held by $_.status equal to "Running" and not equal "Stopped".
Trap: { $_.status = "Running"} Remember that PowerShell introduces comparisons with a
hyphen
and not an equal sign, thus we have -eq -match, -contains.
Guy Recommends: SolarWinds LANSurveyor
LANSurveyor will produce a neat diagram of your network topology. But that's
just the start;
LANSurveyor can
create an inventory of the hardware and software
of your machines and network devices. Other neat features include dynamic
update for when you add new devices to your network. I also love the ability to export
the diagrams
to Microsoft Visio.
Finally, Guy bets that if you take a free trial of LANSurveyor then you will
find a device on your network that you had forgotten about, or someone else
installed without you realizing!
Assumptions: You saved the cmdlet script files into a directory called D:\ scripts. Also, in my example I assume that the actual file is called RunningServices.ps1.
When you execute the cmdlet by calling the filename from the PowerShell command line, you don't need to add the .ps1 extension. However, you need to pay attention to the path. Start
at the command line by typing the full path, for example, D:\ scripts\RunningServices.
When that works, build on success.
Navigate in PowerShell to the D:\ scripts folder, to achieve that, you could try this command
set-location d:\ scripts Now issue the shorter command: .\RunningServices (Rather than D:\ scripts\RunningServices)
Note: Observe the dot and the slash in front of the filename, incidentally the slash can be either
a backslash or a forward-slash, therefore, ./runningservices works.
If, for what ever reason, you do not wish to use a cmdlet,
the alternative is to copy instructions from notepad and then paste them into the PowerShell interface.
When you execute PowerShell commands you have a choice, either just type the instructions at the Microsoft Shell
command line, or create cmdlets scripts which you then call from the PS > prompt. Remember before you start experimenting with PowerShell scripts, change the
ExecutionPolicy to RemoteSigned. To
enable scripts to run locally, type
this command: set-ExecutionPolicy RemoteSigned.
As a result the PowerShell registry will now permit .ps1 files to execute at the PowerShell command line.
If you see an error of any kind, do let me know. Please report any factual mistakes, grammatical errors or broken links, I will be happy to not only to correct the fault, but also to give you credit.
*
Guy
Recommends: Orion's NPM - Network Performance Monitor
Orion's performance monitor is designed for detecting network outages.
A network-centric
view make it easy to see what's working, and what needs your attention.
This utility guides you through troubleshooting by indicating whether the
root cause is faulty equipment or resource overload.