Powershell Script Base

1 minute read

Easy powershell function template:

# VERY USEFUL:
# https://adamtheautomator.com/powershell-functions/

function Personal-Function {
	[CmdletBinding()]
	param(
	  [Parameter(Mandatory)]
	  [string] $UserPrincipalID
	)

  Write-Host "Hey ho "$UserPrincipalID
}

Save as myfunction.ps1, execute like this:

C:\Blabla> . ./myfunction.ps1
C:\Blabla> Personal-Function my-principal-id
Hey ho my-principal-id
C:\Blabla> _

Note: Load with . .\myfunction.ps1 (note the two dots at the start) because you don’t want to execute the file in a sub-process, you want to load the file in this process.

  • if you load it using .\myfunction.ps1 (which will “work”), a new sub-shell is spawned, which loads the file, does nothing, and ends.
  • so the currently active shell does now know about the function, cause it was only ever evaluated in the sub-shell which already quit
  • same as with *nix (the source or . command)

(PS: Powershell syntax highlighting should work, but doesn’t. Uncool.)