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.
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.
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With