How-to: PowerShell script template

The template below can be used as a starting point for new PowerShell scripts. The template has sections for Declarations, Functions and the main body of the script.

# MyScript.ps1
[CmdletBinding()]

PARAM ( 
    [string]$InitialDirectory = $(throw "-InitialDirectory is required."),
    [switch]$YesNoSwitch = $false
)

# Consider adding some comment based help for the script here.


#----------------[ Declarations ]----------------

# Set Error Action
$ErrorActionPreference = "Continue"

# Dot Source any required Function Libraries
. "C:\Scripts\Functions.ps1"

# Set any initial values
$Examplefile = "C:\scripts\example.txt"

#----------------[ Functions ]------------------
Function MyFunction1{
  Param()
  # Consider adding some comment based help for the function here.
  # main body of function1
}

Function MyFunction2{
  Param()
  # Consider adding some comment based help for the function here.
  # main body of function2
}

#----------------[ Main Execution ]---------------

# Script Execution goes here
# and can call any of the functions above.

“We take this template ... and act as if it's God-given, ... We don't see that this was a social invention and we can re-invent it. We as a society need to create new templates for work life” ~ Phyllis Moen

Related PowerShell Cmdlets:

Advanced Functions a template to copy with more detail on the parameters available.
Run a script - How to run a PowerShell script.
Functions - Write a named block of code.


 
Copyright © SS64.com 1999-2020
Some rights reserved