Daily Archives: 08/08/2012

PowerShell – Modularize your scripts

Boy I’m on a roll this week. Two posts in as many days. Mustn’t be anything good on the TV.

How many times have you created a cool piece of code in one of your scripts and thought

“Damn that is a cool piece of code. I can use this in other scripts”

I found myself often cutting and pasting these cool bits from previous scritps into my new ones. Then I learnt about creating your own modules for PowerShell (for code cutters out there your probably saying “Uh  Duh!”, all I can say in my defence is “Cut me so slack I’m a programming Noob”).

How do you do that? It’s actually pretty simple. Lets take a very basic piece of code I use for placing a timer in a script. I sometimes use this when I need to allow a pause for either replication or to give something sufficient time to complete an external process.

I took this code and placed into a Function Statement creating a function name that followed the basic rules of powershell commandlets. Within this function I put the body of my script. I then added an Export-ModuleMember command at the end then saved the whole lot as a .psm1 file. Below is the script I was talking about

# Count down for powershell showing progress bar
# Edit value x for the length needed
# This module is 20 seconds

function get-timer {
$x = 20
$length = $x / 100
while($x -gt 0) {
$min = [int](([string]($x/60)).split('.')[0])
$text = " " + $min + " minutes " + ($x % 60) + " seconds left"
Write-Progress "Pausing Script" -status $text -perc ($x/$length)
start-sleep -s 1
$x--
}
}
Export-ModuleMember get-timer

I then saved the .psm1 file in the Powershell module directory in a subfolder (called the same as my module for easier reference).

So now whenever I want to add a timer in my script, rather than type the whole mess of code, I simply add the following line at the top of my script

Import-Module ModuleName (where ModuleName is the actual module directory you created)

I then simply add get-timer into the script where I want the timer to appear and hey presto you have created a module for powershell.

Hope this helps make your scripting projects as much fun as mine Matrix


Translator

Tag Cloud