Create PowerShell cmdlet using PowerShell
Do you know that you can build PowerShell cmdlets using PowerShell code? I used CSharp in the past, but the times has changed. Our SharePoint provisioning requirements change so fast that we find it easy to use PowerShell for all instead of CSharp to create the cmdlet and then use PowerShell to invoke it. Here is another PowerShell tip that I'd like to share and have it in my blog so I never have to search the network again.
This is a simple snippet that shows how we can create PowerShell module using PowerShell code.
You can create file with PSM1 extension like MyScript.psm1 and the code can look like:
Usage in a .ps1 script file is like:
So that module can be imported in other psm1 module the same way I imported the Common.psm1 on the top of the script.
The use of $PSScriptRoot could be handy if multiple psm1 files nested in folders
I noticed that the use of $PSScriptRoot is very handy for me when I have multiple .psm1 modules in a nested folders structure. Using $PSScriptRoot will give us the option to use the top level .psm1 cmdles with all the imports and execute commands, but also allows the nested in folder psm1 files to be executed separately as stand alone modules.
Use Import-Module -Force when you do debugging
The Force param will ensure that any changes made in the imported file are loaded again. If force param is not present the first import is cached and any changes made to that will not be present even when you attempt to import it again without -Force param.
Having the option to create a cmdlet in PowerShell directly is super handy and we can be really flexible in our day to day DevOps or other automation tasks.