How can I re-use/import script code in PowerShell scripts?

Common Code In Powershell

You can just put the code you want to include in a different PS1 file, and then “dot source” that file to include it in the current scope:

. D:\script_common\MyCode.ps1

That’s all there is to that.

Using a Module

You might consider using a module instead, which can be included using the Import-Module cmdlet. You might have used this to work with things like Active Directory, where you could do something like this:

Import-Module ActiveDirectory

In that case, you only need the name of the module because it’s in a special directory.

To write your own modules in Powershell, you name the module with a .psm1 extension. Typically, you don’t do free floating code in one of these; you write functions which are then available to the code which imports the module.

To import a script module from anywhere, use the full path:

Import-Module D:\script_common\MyModule.psm1

Module Paths

When you create your own modules, you can keep them any old place and then refer to them by their full path (as above). There are also several locations that Powershell looks for modules:

  • $PSHome\Modules (%Windir%\System32\WindowsPowerShell\v1.0\Modules) — Reserved for modules that ship with Windows. Do not put things here.
  • $Home\Documents\WindowsPowerShell\Modules (%UserProfile%\Documents\WindowsPowerShell\Modules)
  • %ProgramFiles%\WindowsPowerShell\Modules — this isn’t mentioned in the link, and seems to be used more for Desired State Configuration modules (probably because it applies to the entire system).

These are defaults, but Powershell uses its own environment variable called PSModulePath to determine where to look, and much like PATH you can add your own folder(s) to that variable.

That lets you keep your modules in your own location. Do see the link for more info on how to structure your folders and how to do naming.

So as far as keeping your modules and “3rd party” modules in the same place, that depends on the 3rd party stuff. It may install its own modules in its own place and modify the path, or it may just let you put them wherever you want.

Creating a Temp Folder

You can use the TEMP or TMP environment variables to get the path of the temp folder. To retrieve them in Powershell, use $env:TEMP or $env:TMP.

You’ll have to come up with a unique name of a folder to create in there. One way to do that might be to use a GUID:

$dirName = [System.Guid]::NewGuid().ToString()
New-Item -Path "$($env:TEMP)\$dirName"

Leave a Comment