powershell PowerShell脚本模板

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了powershell PowerShell脚本模板相关的知识,希望对你有一定的参考价值。

<#
****************************************************************************
* {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 
}

以上是关于powershell PowerShell脚本模板的主要内容,如果未能解决你的问题,请参考以下文章

powershell PowerShell:脚本模板版本2(无需记录)

powershell PowerShell脚本模板

powershell PowerShell:脚本模板

powershell PowerShell:脚本模板版本2(带日志记录)

powershell 具有已保存信用的PowerShell脚本模板

powershell Powershell脚本复制网站然后多次使用它,有点像模板。