PowerShell has been a sneaky beast whose power is just now starting to creep into my programming psyche. Being the good OO citizen that I am I immediately started wanting to modularize my PowerShell scripts and functions for maximum re-use and easy organisation.
There are a number of ways to modularize your PowerShell including (but probably not limited to!):
- (Not recommended) Breaking down script blocks into functions and organising code consistently within the single .ps1 script file
- Organising functions into multiple individual .ps1 script files and dot-sourcing them
- TIP: Make use of Get-ScriptDirectory function to form relative paths from your current script location
- For most effective use, it’s recommended to keep only functions defined in your dot-sourced scripts and call them individually.
- Organising repeatable script blocks into multiple individual .ps1 script files that are parameterised and call them using the Call operator (& ) [See Kirk’s link why dot-sourcing should be avoided]
- Note: I’m not talking about using functions, rather a normal .ps1 script with inline calls
- See Kirk’s great post on invoking or calling scripts within scripts
- Remember, anything used with the return keyword is what is assignable when using call operators (. and & )
- Anything that is output to host can be piped into certain host/stream redirection cmdlets (e.g. Out-File, Out-Null, Out-String)
- Defining functions in your user or system profile (Profile.ps1)
- Remember, this could be a deployment and backup problem
- Writing .NET compiled cmdlets
- Compiled functions written in .NET languages and deployed in specially attributed assemblies and then specifically registered into PowerShell