Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing "libraries" in powershell

I'm finding myself writing a bunch of related functions dealing with different nouns (clusters, sql servers, servers in general, files, etc.) and put each of these groups of functions in separate files (say cluster_utils.ps1, for example). I want to be able to "import" some of these libraries in my profile and others in my powershell session if I need them. I have written 2 functions that seem to solve the problem, but since I've only been using powershell for a month I thought I'd ask to see if there were any existing "best practice" type scripts I could be using instead.

To use these functions, I dot-source them (in my profile or my session)... for example,

# to load c:\powershellscripts\cluster_utils.ps1 if it isn't already loaded
. require cluster_utils    

Here are the functions:

$global:loaded_scripts=@{}
function require([string]$filename){
      if (!$loaded_scripts[$filename]){
           . c:\powershellscripts\$filename.ps1
           $loaded_scripts[$filename]=get-date
     }
}

function reload($filename){
     . c:\powershellscripts\$filename.ps1
     $loaded_scripts[$filename]=get-date
}

Any feedback would be helpful.

like image 556
Mike Shepard Avatar asked Nov 11 '08 04:11

Mike Shepard


People also ask

How do I import a PowerShell module?

In PowerShell 2.0, you can import a newly-installed PowerShell module with a call to Import-Module cmdlet. In PowerShell 3.0, PowerShell is able to implicitly import a module when one of the functions or cmdlets in the module is called by a user.

How do I permanently import a PowerShell module?

To import PowerShell modules permanently you can copy them creating a folder on C:\Windows\system32\WindowsPowerShell\v1. 0\Modules\ with the name of your script, then inside you can put all your psm1 or ps1 files.


1 Answers

Building on Steven's answer, another improvement might be to allow loading multiple files at once:

$global:scriptdirectory = 'C:\powershellscripts'
$global:loaded_scripts = @{}

function require {
  param(
    [string[]]$filenames=$(throw 'Please specify scripts to load'),
    [string]$path=$scriptdirectory
  )

  $unloadedFilenames = $filenames | where { -not $loaded_scripts[$_] }
  reload $unloadedFilenames $path
}

function reload {
  param(
    [string[]]$filenames=$(throw 'Please specify scripts to reload'),
    [string]$path=$scriptdirectory
  )

  foreach( $filename in $filenames ) {
    . (Join-Path $path $filename)
    $loaded_scripts[$filename] = Get-Date
  }
}
like image 102
Emperor XLII Avatar answered Sep 23 '22 10:09

Emperor XLII