zoltcom
11/10/2017 - 4:06 PM

PowerShell script template

PowerShell script template

<#
****************************************************************************
* {TITLE}
*
* Description
*   {DESCRIPTION}
*
* Dependencies
*   {DEPENDENCIES}
*
* Resources
*   {RESOURCES}
*
* Log
*   20yy-MM-dd: initial version
*
****************************************************************************
#>

# [CmdletBinding()] has several uses, including allowing use of -verbose and -debug switches
[CmdletBinding()]
param(
  [int] $IntParam = 0,
  [string] $StringParam = 'default value',
  [switch] $SwitchParam = $false
)

# variables have to be initialized before they can be used; reduces some bugs
Set-StrictMode -Version 2.0
# Need to globally set error action to stop, otherwise non-terminating errors won't get caught in try/catch blocks
$ErrorActionPreference = 'Stop'

try {
  # File logging
  $timestamp = (get-date -format 'yyyy-MM-ddTHH:mm:ss') + ': '
  $logFile = ($MyInvocation.MyCommand.Path + '.log')
  $scriptPath = Split-Path $MyInvocation.MyCommand.Path
  #Library functions (dot sourced)
  #. (Join-Path $scriptPath Common.ps1)


  $outMsg = $timestamp + 'Some message.'
  
  # write to log
  add-content $logFile ($outMsg)
  
  # write to console if verbose on
  write-verbose $outMsg
  
  # success exit (read with $lastexitcode for value or $? for true(0)/false(non-zero) 
  exit 0

} catch {
  # short error
  $outMsg = $timestamp + 'Error; ' + $_
  # full error and trace
  #$outMsg = $timestamp + 'Error; ' + ($_.Exception|format-list -force | out-string)
  
  # write to log
  add-content $logFile ($outMsg)
  
  # write to console 
  write-host $outMsg

  # error exit (anything other than 0) (read with $lastexitcode for value or $? for true(0)/false(non-zero) 
  exit 1 
}