Friday, July 30, 2010

Powershell: Include other scripts in your Powershell script

I don’t used Powershell a lot before. But lately I’m starting to discover more and more of it’s richness and how it can make my life a lot simpler.

One of the things that took me some time to figure was how to include other scripts inside your own Powershell script. Now doing is this is very easy(once you know it).

One way to use functions from another script is to use the dot sourcing operator to run the script so that the functions from the script are part of the calling scope. To dot source the script, you use the dot source operator (a period) followed by the path to the script containing the functions you wish to include in your current scope. After you do this, you can call the functions from the other script directly.

An example:

PS C:\> . C:\scripts\ConversionFunctions.ps1
PS C:\> convertToMiles 6
6 kilometers equals 3.7266 miles

1 comment:

Joachim said...

When i use the . method to include a script with functions all works fine until I run it with task scheduler (Server 2008 R2). All scripts then end with a 0x41306. Before I used the . to incldude functions the tasks worked fine. Running them directly is fine too.

That's how I include my functions
. \\servername\scripts$\library.ps1

Do you have any idea how I can get this to work with the task scheduler?

Cheers
Joachim