As part of a recent project I’ve needed to work closely with some of the Azure api’s. You can achieve some really cool things pretty quickly once you’ve learnt a few basics.
A good tip I picked up was that if you can implement something in .net/c# chance are you can replicate in PowerShell. If there isn’t a specific PowerShell module/api available you can call into the .net dll. This can be loaded via e.g.:
1 2 3 4 5 6 |
function CurrentDirectory { return (split-path $SCRIPT:MyInvocation.MyCommand.Path -parent); } [System.Reflection.Assembly]::LoadFrom((CurrentDirectory) + '\Microsoft.WindowsAzure.Storage.dll') $credentials = New-Object Microsoft.WindowsAzure.Storage.Auth.StorageCredentials($accountName, $accountKey) |
In order to structure your various functions the recommended approach is to use modules. A quick google will bring up more details. What I couldn’t find was how to setup a basic module that includes multiple scripts.
When you create new modules they can live in a couple places, $env:PSModulePath will show you this.
A module structure is pretty basic, you need a psm1 file (and psd1 – see https://www.simple-talk.com/sysadmin/powershell/an-introduction-to-powershell-modules/)
Script.ps1 is basic, it contains a simple function:
1 2 3 4 |
function HiThere { return "hi there"; } |
Custom.psm1 then looks to load all the scripts you have. Note, make sure the folder name matches the psm1 name:
1 2 3 4 5 6 |
$functions = Get-ChildItem -Recurse "$PSScriptRoot\Subfolder" -Include *.ps1 # dot source the individual scripts that make-up this module foreach ($function in $functions) { . $function.FullName } Write-Host -ForegroundColor Green "Module $(Split-Path $PSScriptRoot -Leaf) was successfully loaded." |
These files need to live in one of your module folders e.g. %UserProfile%\Documents\WindowsPowerShell\Modules
It’s then a case of installing your module:
Check what modules are available to install via: Get-Module -ListAvailable
And install the one you want via: Import-Module Custom. Note, Custom is the name of the folders and psm1 file.
Provided it’s all gone to plan you should now be able to call HiThere from a ps prompt