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:


Import-Module $PSScriptRoot/../../Common.psm1 -Force

function New-BusinessProfileSite {
    
   # YOUR PARAMETERS HERE
   param(
        [parameter(Mandatory=$true)]$SiteFullUrl,
        [parameter(Mandatory=$true)]$Creds,
        $Owners,
        [switch]$SkipUploadPackages
    )

   Write-Host "$PSScriptRoot\MyScript.psm1 has started"

   # YOUR CODE HERE
   # YOU CAN INVOKE FUNCTIONS FROM THE COMMON.PSM1 THAT WAS IMPORTED AS WELL

    Write-Host "DONE"
}

Export-ModuleMember -Function * -Alias * -Variable *

Usage in a .ps1 script file is like:


Import-Module C:\<PATH TO THE FILE>\ProvisionBusinessProfile.psm1

New-BusinessProfileSite  -SiteFullUrl <URL> -Creds <CREDS>  -SkipUploadPackages

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.


Import-Module $PSScriptRoot/../../Common.psm1 -Force

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.

Conclusion

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.

Posted on

Tags: PowerShell tip, SharePoint provisioning, Office 365, PowerShell cmdlet, PowerShell function, psm1, ps1

Comments