Skip to content

Instantly share code, notes, and snippets.

@kayasax
Last active December 22, 2015 19:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kayasax/6521340 to your computer and use it in GitHub Desktop.
Save kayasax/6521340 to your computer and use it in GitHub Desktop.
Template for powershell script. Makes all errors "terminating" and send mail if error occurs
# Templata.ps1
# author: Loic MICHEL
# date: 10/09/2013
# abstract: make all errors terminating errors and send email + raise event in case of failure
#
[CmdletBinding()]param(
)
# GENERATION D'UNE TRACE POUR DEBUGGAGE
#########################################
$erroractionPreference="stop" #toutes les erreurs seront bloquantes
$trace="E:\exploitation\logs\trace_copie_bases_industria.txt"
try{stop-transcript -ea silentlycontinue }catch{} #suppression d'une éventuelle trace antérieure
start-transcript -path $trace
# VARIABLES PRIVEES
#####################
$_scriptname=$MyInvocation.myCommand.definition
$_enc=[system.text.encoding]::UTF8 #encoding à utiliser pour le mail
# *** !! VARIABLES A MODIFIER !! ***
###########################################
$source="f:\SQLBACKUP\" #répertoire de base des sauvegardes SQL
$destination="\\indus2-msons\SQLBACKUP" #destination de la sauvegarde
$logdir="e:\exploitation\logs"
$description="Copie bases INDUSTRIA LANTERNEAUX sur INDUS2-MSONS" #la description sera réutilisée dans les messages logs et mails
$bdd='AXTER LA' # si $midi est utilisé, seule cette base sera copiée.
$message="Erreur : $description ($_scriptname)" #sujet des mails
$from="$env:computername@domain.com" #expediteur pour mail
$to="user@domain.com","user2@dom.com" #
$PSEmailServer="smtpinterne.domain.com" #adresse du serveur smtp
# DEBUT DU SCRIPT
#################
get-date
"`tDébut du script"
try{
#DO STUFF
}
catch{ # Gestion des erreurs blocantes
write-host "Une erreur est survenue !"
$_
copy-item $trace $logdir\trace2.txt -force
$msg=$message + $($_.Exception.Message)
Write-EventLog application -EntryType error -Source SMACINFO -eventID 1 -Message $msg
send-mailmessage -encoding $_enc -subject $message -bodyasHTML "$($_.Exception.toString() )<br/> " -to $to -from $from -attachments $logdir\trace2.txt
$?
stop-transcript
break
}
get-date
"Fin normale du script"
stop-transcript
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment