In this post i will show my variant of powershell-code organization.
Main objectives:
- Minimum copying of myself
- Easy structure
- Reusable
- Flexibility
- SharePoint oriented
As for SharePoint oriented: if you use Visual Studio Code for powershell-development, you should read this post first: VisualStudioCode – PowerShell stubs for SharePoint.
Code organization concepts:
- Dot-sourcing
- Modules
Dot-Sourcing:
This concept based on specific script call (mask is: . .\script.ps1). Due such execution, all variables that used in script.ps1 will exist in current context (from where you calling script1.ps1). Notice, that when script executes ordinarily, it has mask: .\script.ps1.
Example:
For example, we have script:
1 2 |
$answer="42" write-output "ultimate answer is $answer" |
Lets see how it will be executed ordinarily:
1 2 3 4 |
PS D:\temp> .\script.ps1 ultimate answer is 42 PS D:\temp> $answer |
And execution as dot-sourced:
1 2 3 4 5 |
PS D:\temp> . .\script.ps1 ultimate answer is 42 PS D:\temp> $answer 42 |
As you can see, after ordinarily execution, internal variable $answer do not exists in parent context. In dot sourcing it does.
Modules
This concept based on 2 entities: module manifest and module.
Module contains all logic of PowerShell script (such as functions, that you want be exported). Module manifest – easy format to describe this module (which functions will be exported, from where and so on).
Let see module in details. For example, i have my Web.psm1 module in powershell-sharepoint repo:
1 2 3 4 5 6 7 8 |
function Get-List-On-Web { Param( [Microsoft.SharePoint.SPWeb] $web, [string] $listUrl ) return $web.GetList($web.Url + '/lists/' + $listUrl) } |
As you can see, it is a typical function. This Web.psm1 file placed in separate folder named “Web” in utils folder. So, the structure is:
1 2 3 4 5 |
+---scenarios \---utils \---Web Web.psd1 Web.psm1 |
Near Web.psm1 is also created Web.psd1 file (manifest-file).
Command for creating manifest file (described here = [link])
1 |
New-ModuleManifest -Path C:\ps-test\Test-Module\Test-Module.psd1 -PassThru |
Lets see what manifest file contains:
Most important lines here are:
- RootModule – path to *.psm1 with logic of module
- FunctionsToExport – array of function names that will be exported from module
- You can type wildcard * here, but it’s not recommended
Basic scenario that uses logic function from external module listed below:
1 2 3 4 5 6 7 8 9 10 |
Add-PSSnapin Microsoft.Sharepoint.Powershell .\Load-Module.ps1 Web $siteUrl = "http://bot-sp2016/" $webUrl = "http://bot-sp2016/SalesManagement/" $list = "Sale" $web = Get-SPWeb $webUrl $list = Get-List-On-Web $web $list |
LoadModule.ps1 – is helper script for easy Import-Module using from 1 central utility storage:
1 2 3 4 5 |
Param( [string] $moduleName ) Import-Module $PSScriptRoot\..\utils\$moduleName -Force |