I put my personal scripts in the same folder as my profile. I can then back up & version them together. My profile begins with:
$ProfileRoot = (Split-Path -Parent $MyInvocation.MyCommand.Path)
$env:path += ";$ProfileRoot"
My recommendations: - Store the script in a directory as you wish, e.g. c:\posh - Add the directory to $env:path
$env:path += ";c:\posh"
This ensures that you may be in other directory, say c:\windows, but you can call the script
[c:\windows] > sampl[TAB] # it expands the name of file to sample.ps1, then hit enter
If your file sample.ps1 contains functions definitions and you import it every time, then I would consider adding this line to your $profile file
. c:\posh\sample.ps1
Concerning script organization.. just several dirs according to the purpose of the scripts :) Personal, dev, external (downloaded), samples,...
With V2, you can create a modules directory in the WindowsPowerShell directory where your profile is. PS will automatically look in that directory to load modules when you run import-module. I created a "Scripts" directory under WindowsPowerShell as well that is a sibling directory of Modules.
I use my profile to set some directories using variables with the following code:
PS> cat $Profile
$scripts = "$(split-path $profile)\Scripts"
$modules = "$(split-path $profile)\Modules"
$docs = $(resolve-path "$Env:userprofile\documents")
$desktop = $(resolve-path "$Env:userprofile\desktop")
PS> cat variable:\scripts
C:\Users\andy.schneider\Documents\WindowsPowerShell\Scripts
PS> cat variable:\modules
C:\Users\andy.schneider\Documents\WindowsPowerShell\Modules
This is what I do:
note: substitute "ModuleName" for something meaningful.
Create a module and save it in the global modules folder as "C:\Windows\System32\WindowsPowerShell\v1.0\Modules\ModuleName\ModuleName.psm1". e.g.:
function global:FancyFunction() {
# do something interesting here.
}
Export-ModuleMember -function FancyFunction
Open your powershell profile and add the following line to make sure that your module is loaded every time you start a powershell session:
Import-Module ModuleName -Force
You can easiliy find your powershell profile by typing:
notepad $profile
When you open a new powershell session, you should be able to call your function from the console or from other scripts without having to do anything else.
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