PowerShell

 

 

accueil | console | VBScript | PowerShell | php | MySQL | documentation | formation  | trucs et astuces | exemples | glossaire

 

 

{00, 24, 56}

 

(page en cours de rédaction - translation pending, stay tuned)

 

 

 

Foreword for our English-speaking Readers

18-nov-2010

 

When I started the www.scripting-errors.com web site project one month ago, my first idea was to gather enough documentation on Error Handling for Windows System Managers to (try to) publish a book in France. As you may have read in the home page of this site, I spent thirty-one years in the DEC world doing system programming and management, teaching, and Fortran/Cobol/DCL writing. To me, Error Handling should be the main item to focus on. Why? Because of Murphy's Law. It is certainly nice to know everything about .NET, about heritages and about pointers, but these subjects really are a must for Geeks (in French: adolescents boutonneux) only, aren't they? Solving daily operations issues is definitely more important. Fixing a bugged program/script/whatever is matter of time, and time is... You got it.


So, I wrote in here (in French) some stuff on the so-called DOS command window, then much more on VBScript. Last Monday (Monday Monday... [I'm talking about a time that less than twenty years old people may not know]) I started to browse the MSDN and TechNet pages, looking for PowerShell Error Handling. I gathered all I found in four days on this page, below. Sky! More than 70 links to 70 different documents. Gook luck, Didier! And not even one .pdf file to DL. (but this one).

 

In these circumstances, I do think that gathering PowerShell Error Handling stuff in one book may be a concern for more people than the French speaking ones, after all.

 

I'm today proud to humbly announce to the worldwide IT community that the book will be written in English first (and this page below translated to English as soon as it is finished).

 

[Music, applause]

 

Thank you.

 

DTL

 

 


 

I - GENERALITES

(page en cours de rédaction - translation pending, stay tuned)

 

 

PowerShell n'est pas un langage de programmation (contrairement à ce que Microsoft veut nous faire croire) mais un interface de communication entre l'utilisateur et Windows. Il est basé sur le concept d'objets. Toute fonctionnalité de Windows peut devenir un objet. Chaque objet peut être consulté et ses propriétés modifiées. Enfin, ses méthodes permettent de changer son comportement (démarrer ou arrêter un process, par exemple).

 

PowerShell ne sert qu'à interroger des données et à les modifier. La gestion des erreurs sera donc très limitée.

 

Les scripts PowerShell sont des successions de commandes, appelées cmdlets, plus ou moins compliquées.

 

Contrairement à ce que proclame Microsoft sur tous les toits, PowerShell ne peut en aucun cas remplacer VBScript, qui - lui - est un langage de programmation.

 

La documentation de Microsoft mélange allègrement des informations techniques sur l'écriture et la programmation de commandes PowerShell (les cmdlets) et la gestion d'erreurs dans des scripts par PowerShell. Chaque chapitre ci-dessous comportera donc deux parties : une partie qui focalise sur la programmation de la gestion d'erreurs dans des cmdlets écrites par l'utilisateur (essentiellement issue de MSDN), et une autre plus spécifique à la gestion de ces erreurs par PowerShell lorsqu'elles se produisent (source : TechNet). La première section utilisera le mot-clé PROG et la seconde le mot-clé SYSTEM.

 

Si on veut faire un comparatif avec la doc de , pour ceux qui connaissent, MSDN fournit les Reference Manuals, le quoi, et TechNet fournit les Users Guides, le comment. Mais il faut savoir que TechNet est très incomplet par rapport à MSDN. Exemple en image : liste comparative des cmdlets documentées sur TechNet (à gauche) et MSDN (à droite).

 

 


 

II - LA GESTION D'ERREURS DANS L'ENVIRONNEMENT POWERSHELL

(page en cours de rédaction - translation pending, stay tuned)

 

 

Généralités

 

Windows PowerShell Error reporting PROG

http://msdn.microsoft.com/en-us/library/dd878251%28v=VS.85%29.aspx

 

ErrorRecord schema PROG

http://technet.microsoft.com/en-us/library/ee156811.aspx#EDAA

 

ErrorRecord description PROG

http://msdn.microsoft.com/en-us/library/ms714465%28v=VS.85%29.aspx

 

 

Analogies avec VBScript

 

Option Explicit

Set-PSDebug -Strict

http://blogs.technet.com/b/heyscriptingguy/archive/2010/11/12/error-handling-and-exporting-active-directory-users-to-csv.aspx#Q3

 

On error resume next / on error goto 0

$erroractionpreference = "SilentlyContinue" / "Continue" / "Stop" / "Inquire"

http://technet.microsoft.com/en-us/library/ee176921.aspx

 

Err.number
$error[0].errorrecord
http://technet.microsoft.com/en-us/library/ee176919.aspx
 

Err.description

$a = $error[0].ToString()
http://technet.microsoft.com/en-us/library/ee176810.aspx
 

Err.source
$a = $error[0].source
http://technet.microsoft.com/en-us/library/ee176969.aspx

 

Err.helpfile
$a = $error[0].helplink
http://technet.microsoft.com/en-us/library/ee176866.aspx

 

Err.context
$a = $error[0].helplink
http://technet.microsoft.com/en-us/library/ee176865.aspx
 

Err.raise

Throw

http://technet.microsoft.com/en-us/library/dd819510.aspx

 

 

Méthodes de l'objet $Error

 

PS> $error | get-member -membertype method

 

TypeName: System.Management.Automation.ErrorRecord

Name          MemberType Definition
----          ---------- ----------
Equals        Method     bool Equals(System.Object obj)
GetHashCode   Method     int GetHashCode()
GetObjectData Method     System.Void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runti...
GetType       Method     type GetType()
ToString      Method     string ToString()

 

 

Propriétés de l'objet $Error

 

PS> $error | get-member -membertype property

 

TypeName: System.Management.Automation.ErrorRecord

Name                  MemberType      Definition
----                  ----------      ----------
CategoryInfo          Property        System.Management.Automation.ErrorCategoryInfo CategoryInfo {get;}
ErrorDetails          Property        System.Management.Automation.ErrorDetails ErrorDetails {get;set;}
Exception             Property        System.Exception Exception {get;}
FullyQualifiedErrorId Property        System.String FullyQualifiedErrorId {get;}
InvocationInfo        Property        System.Management.Automation.InvocationInfo InvocationInfo {get;}
PipelineIterationInfo Property        System.Collections.ObjectModel.ReadOnlyCollection`1[[System.Int32, mscorlib, Ve...
TargetObject          Property        System.Object TargetObject {get;}
PSMessageDetails      Script Property System.Object PSMessageDetails {get=& { Set-StrictMode -Version 1; $this.Except...

 

 

Fonctions High Level et Low Level

 

Write-Debug("Hello!")

 

L'affichage de ce texte dépend de la variable de préférence $DebugPreference (valeur par défaut : "SilentlyContinue")

car Write-Debug est une cmdlet High Level, soumise aux options d'environnement de PowerShell.

 

mais

 

$host.ui.WriteDebugLine("Hello!")

 

L'affichage de ce texte ne dépend pas de la variable de préférence $DebugPreference

car $host.ui.WriteDebugLine  est une méthode de l'objet $host, une fonction Low Level indépendante des options d'environnement de PowerShell.

 

Exemple :

 

PS C:\powershell> $debugpreference
SilentlyContinue

PS C:\powershell> Write-Debug("Hello!")
PS C:\powershell> $host.ui.WriteDebugLine("Hello!")
DEBUG: Hello!

PS C:\powershell>

 

 

 

 

 

 

 

 

 

 

 


tbs

 


 

III - PROGRAMMATION DE LA GESTION DES ERREURS DANS UN SCRIPT POWERSHELL

(page en cours de rédaction - translation pending, stay tuned)

 

 

 

ATTENTION

 

Avec PowerShell, contrairement à VBScript, toutes les fonctions et subroutines doivent être placées avant

le programme principal (main), sinon elles ne sont pas déclarées.

 

 

 

(this page build thanks to Brandon Shell [yes, that is his name])

 

$? Automatic error variable. Boolean : False if error occurred (???) SYSTEM

http://technet.microsoft.com/en-us/library/dd347675.aspx

 

Exemple :

 

if (-not $?) { error handler }

 

 

$_ Automatic variable. SYSTEM

http://technet.microsoft.com/en-us/library/dd347675.aspx

 

 

Clear() méthode de l'objet $Error qui réinitialise la dernière ou les 256 dernières erreurs rencontrées. SYSTEM

http://technet.microsoft.com/en-us/library/ee156809.aspx

 

 

$Error : object. SYSTEM

http://msdn.microsoft.com/en-us/library/system.management.automation.psdatastreams.error%28v=VS.85%29.aspx

 

 

$ErrorActionPreference : Preference variable. Determines the default action if error is thrown. SYSTEM / PROG

http://technet.microsoft.com/en-us/library/dd347731.aspx

http://msdn.microsoft.com/en-us/library/system.management.automation.actionpreference%28VS.85%29.aspx

 

 

ErrorCategory SYSTEM

http://msdn.microsoft.com/en-us/library/system.management.automation.errorcategory%28v=VS.85%29.aspx

 

 

ErrorCategoryInfo class / SYSTEM

http://msdn.microsoft.com/en-us/library/system.management.automation.errorcategoryinfo%28v=VS.85%29.aspx

 

 

ErrorDetails class / SYSTEM

http://msdn.microsoft.com/en-us/library/system.management.automation.errordetails%28v=VS.85%29.aspx

 

 

ErrorRecord class / SYSTEM

http://msdn.microsoft.com/en-us/library/ms714465%28v=VS.85%29.aspx

 

 

$ErrorView : Preference variable. This is how the error will output to the screen. SYSTEM

http://technet.microsoft.com/en-us/library/dd347731.aspx

http://msdn.microsoft.com/en-us/library/dd878266%28v=VS.85%29.aspx

 

 

InvocationInfo : This contains detail information about the command that was run. SYSTEM

http://blogs.technet.com/b/heyscriptingguy/archive/2010/03/11/hey-scripting-guy-march-11-2010.aspx

 

 

$lastexitcode Automatic variable. SYSTEM

http://technet.microsoft.com/en-us/library/dd347675.aspx

 

 

$MaximumErrorCount : Preference variable. Total number of Error objects that will be saved in $Error. SYSTEM

http://technet.microsoft.com/en-us/library/dd347731.aspx

 

 

Set-PSDebug SYSTEM

http://technet.microsoft.com/en-us/library/dd315302.aspx

 

 

System.Exception.Message PROG

http://msdn.microsoft.com/en-us/library/system.exception.message%28v=VS.85%29.aspx

 

 

TargetObject c'est une propriété de l'objet ErrorRecord. PROG

http://msdn.microsoft.com/en-us/library/ff437199%28v=EXCHG.140%29.aspx

 

 

Throw PROG

http://technet.microsoft.com/en-us/library/dd819510.aspx

http://msdn.microsoft.com/en-us/library/xhcbs8fz.aspx

 

ThrowTerminatingError PROG

http://msdn.microsoft.com/en-us/library/system.management.automation.cmdlet.throwterminatingerror%28v=VS.85%29.aspx

 

 

Trace-Command PROG

http://technet.microsoft.com/en-us/library/dd315284.aspx

 

 

Trap PROG

http://technet.microsoft.com/en-us/library/dd347548.aspx

 

Exemple :

 

http://blogs.technet.com/b/heyscriptingguy/archive/2009/08/07/hey-scripting-guy-quick-hits-friday-the-scripting-guys-respond-to-a-bunch-of-questions-8-7-09.aspx

 

# ------------------------------------------------------------------------
# NAME: DemoTrapSystemException.ps1
# AUTHOR: ed wilson, Microsoft
# DATE: 8/6/2009
#
# KEYWORDS: Demo, Error Trap, Trap Error
#
# COMMENTS: This illustrates trapping an error.
# $ErrorActionPreference will control NON-Terminating errors.
# Trap will control Terminating errors.
# Try the different error action preferences: stop, continue, silentlycontinue, inquire
# [SystemException] is the grand daddy of all exceptions.
# ------------------------------------------------------------------------
Function My-Test( [int]$myinput)
{
 
 "It worked"
} #End my-test function
# *** Entry Point to Script ***

#$ErrorActionPreference = "Stop"
Trap [SystemException] { "error trapped" ; continue }
My-Test -myinput "string"
"After the error"
>

 

 

Try ... Catch ... Finally PROG

http://technet.microsoft.com/en-us/library/dd315350.aspx

http://msdn.microsoft.com/en-us/library/xtd0s8kd.aspx

http://msdn.microsoft.com/en-us/library/3tca6706.aspx

http://msdn.microsoft.com/en-us/library/ke0zf0f5.aspx

 

 

WarningPreference : Preference variable. SYSTEM

http://technet.microsoft.com/en-us/library/dd347731.aspx

 


WriteError PROG / SYSTEM

http://technet.microsoft.com/en-us/library/dd315265.aspx

http://msdn.microsoft.com/en-us/library/system.management.automation.cmdlet.writeerror%28v=VS.85%29.aspx

 

 

Liste des variables automatiques

 

 

    $$
    $?  
    $^
    $_
    $Args
    $ConsoleFileName
    $Error
    $Event
    $EventSubscriber
    $ExecutionContext
    $False
    $ForEach
    $Home
    $Host
    $Input
    $LastExitCode
    $Matches
    $MyInvocation
    $NestedPromptLevel
    $NULL
    $PID
    $Profile
    $PSBoundParameters
    $PsCmdlet
    $PsCulture
    $PSDebugContext
    $PsHome
    $PSScriptRoot
    $PSSenderInfo
    $PsUICulture
    $PsVersionTable
    $Pwd
    $ReportErrorShowExceptionClass
    $ReportErrorShowInnerException
    $ReportErrorShowSource
    $ReportErrorShowStackTrace
    $Sender
    $ShellID
    $SourceArgs
    $SourceEventArgs
    $StackTrace
    $This
    $True

 

 

 

$$
Contains the last token in the last line received by the session.

$?
Contains the execution status of the last operation. It contains
TRUE if the last operation succeeded and FALSE if it failed.

$^
Contains the first token in the last line received by the session.

$_
Contains the current object in the pipeline object. You can use this
variable in commands that perform an action on every object or on
selected objects in a pipeline.

$Args
Contains an array of the undeclared parameters and/or parameter
values that are passed to a function, script, or script block.
When you create a function, you can declare the parameters by using the
param keyword or by adding a comma-separated list of parameters in
parentheses after the function name.

$ConsoleFileName
Contains the path of the console file (.psc1) that was most
recently used in the session. This variable is populated when
you start Windows PowerShell with the PSConsoleFile parameter or
when you use the Export-Console cmdlet to export snap-in names to a
console file.

When you use the Export-Console cmdlet without parameters, it
automatically updates the console file that was most recently
used in the session. You can use this automatic variable to determine
which file will be updated.

$Error
Contains an array of error objects that represent the most
recent errors. The most recent error is the first error object in the
array ($Error[0]).

$Event
Contains a PSEventArgs object that represents the event that is being
processed. This variable is populated only within the Action block of
an event registration command, such as Register-ObjectEvent. The value
of this variable is the same object that the Get-Event cmdlet returns.
Therefore, you can use the properties of the $Event variable, such as
$Event.TimeGenerated , in an Action script block.

$EventSubscriber
Contains a PSEventSubscriber object that represents the event subscriber
of the event that is being processed. This variable is populated only
within the Action block of an event registration command. The value of
this variable is the same object that the Get-EventSubscriber cmdlet
returns.

$ExecutionContext
Contains an EngineIntrinsics object that represents the
execution context of the Windows PowerShell host. You can
use this variable to find the execution objects that are
available to cmdlets.

$False
Contains FALSE. You can use this variable to represent
FALSE in commands and scripts instead of using the string "false".
The string can be interpreted as TRUE if it is converted to a non-empty
string or to a non-zero integer.

$ForEach
Contains the enumerator of a ForEach-Object loop. You can use the
properties and methods of enumerators on the value of the $ForEach
variable. This variable exists only while the For loop is running. It
is deleted when the loop is completed.

$Home
Contains the full path of the user's home directory. This variable is
the equivalent of the %homedrive%%homepath% environment variables,
typically C:\Documents and Settings\<user>.

$Host
Contains an object that represents the current host application
for Windows PowerShell. You can use this variable to represent the
current host in commands or to display or change the properties of
the host, such as $Host.version or $Host.CurrentCulture, or
$host.ui.rawui.setbackgroundcolor("Red").

$Input
An enumerator that contains the input that is passed to a function. The
$Input variable is case-sensitive and is available only in functions and
in script blocks. (Script blocks are essentially unnamed functions.)
In the Process block of a function, the $Input variable contains the
object that is currently in the pipeline. When the Process block is
completed, the value of $Input is NULL. If the function does not have a
Process block, the value of $Input is available to the End block, and it
contains all the input to the function.

$LastExitCode
Contains the exit code of the last Windows-based program that was run.

$Matches
The $Matches variable works with the -match and -not match operators.
When you submit scalar input to the -match or -notmatch operator, and
either one detects a match, they return a Boolean value and populate
the $Matches automatic variable with a hash table of any string values
that were matched. For more information about the -match operator, see
about_comparison_operators.

$MyInvocation
Contains an object with information about the current command, such as
a script, function, or script block. You can use the information in the
object, such as the path and file name of the script
($myinvocation.mycommand.path) or the name of a function
($myinvocation.mycommand.name) to identify the current command. This is
particularly useful for finding the name of the script that is running.

$NestedPromptLevel
Contains the current prompt level. A value of 0 indicates the original
prompt level. The value is incremented when you enter a nested level and
decremented when you exit it.

For example, Windows PowerShell presents a nested command prompt when
you use the $Host.EnterNestedPrompt method. Windows PowerShell also
presents a nested command prompt when you reach a breakpoint in the
Windows PowerShell debugger.

When you enter a nested prompt, Windows PowerShell pauses the current
command, saves the execution context, and increments the value of
the $NestedPromptLevel variable. To create additional nested command
prompts (up to 128 levels) or to return to the original command prompt,
complete the command, or type "exit".

The $NestedPromptLevel variable helps you track the prompt level. You
can create an alternative Windows PowerShell command prompt that
includes this value so that it is always visible.

$NULL
Contains a NULL or empty value. You can use this variable to
represent NULL in commands and scripts instead of using the string
"NULL". The string can be interpreted as TRUE if it is converted to a
non-empty string or a non-zero integer.

$PID
Contains the process identifier (PID) of the process that is hosting
the current Windows PowerShell session.

$Profile
Contains the full path of the Windows PowerShell profile for the
current user and the current host application. You can use this variable
to represent the profile in commands. For example, you can use it in
a command to determine whether a profile has been created:

test-path $profile

Or, you can use it in a command to create a profile:

new-item -type file -path $pshome -force

You can also use it in a command to open the profile in Notepad:

notepad $profile

$PSBoundParameters
Contains a dictionary of the active parameters and their current
values. This variable has a value only in a scope where parameters
are declared, such as a script or function. You can use it to
display or change the current values of parameters or to pass
parameter values to another script or function.

For example:

function test {
param($a, $b)

# Display the parameters in dictionary format.
$psboundparameters

# Call the Test1 function with $a and $b.
test1 @psboundparameters
}

$PsCmdlet
Contains an object that represents the cmdlet or advanced function
that is being run.

You can use the properties and methods of the object in your cmdlet
or function code to respond to the conditions of use. For example,
the ParameterSetName property contains the name of the parameter set
that is being used, and the ShouldProcess method adds the WhatIf and
Confirm parameters to the cmdlet dynamically.

For more information about the $PSCmdlet automatic variable, see
about_Functions_Advanced.

$PsCulture
Contains the name of the culture currently in use in the operating
system. The culture determines the display format of items such
as numbers, currrency, and dates. This is the value of the
System.Globalization.CultureInfo.CurrentCulture.Name property of the
system. To get the System.Globalization.CultureInfo object for the
system, use the Get-Culture cmdlet.

$PSDebugContext
While debugging, this variable contains information about the
debugging environment. Otherwise, it contains a NULL value.
As a result, you can use it to indicate whether the debugger has
control. When populated, it contains a PsDebugContext object that has
Breakpoints and InvocationInfo properties. The InvocationInfo property
has several useful properties, including the Location property. The
Location property indicates the path of the script that is being
debugged.

$PsHome
Contains the full path of the installation directory for Windows
PowerShell, typically, %windir%\System32\WindowsPowerShell\v1.0. You
can use this variable in the paths of Windows PowerShell files. For
example, the following command searches the conceptual Help topics for
the word "variable":

select-string -pattern variable -path $pshome\*.txt

$PSScriptRoot
Contains the directory from which the script module is being executed.
This variable allows scripts to use the module path to access other
resources.

$PsUICulture
Contains the name of the user interface (UI) culture that is currently
in use in the operating system. The UI culture determines which text
strings are used for user interface elements, such as menus and
messages. This is the value of the
System.Globalization.CultureInfo.CurrentUICulture.Name property of the
system. To get the System.Globalization.CultureInfo object for the
system, use the Get-UICulture cmdlet.

$PsVersionTable
Contains a read-only hash table that displays details about the
version of Windows PowerShell that is running in the current session.
The table includes the following items:

CLRVersion: The version of the common language runtime (CLR)

BuildVersion: The build number of the current version

PSVersion: The Windows PowerShell version number

WSManStackVersion: The version number of the WS-Management stack

PSCompatibleVersions: Versions of Windows PowerShell that are
compatible with the current version

SerializationVersion The version of the serialization method

PSRemotingProtocolVersion
The version of the Windows PowerShell remote
management protocol

$Pwd
Contains a path object that represents the full path of the current
directory.

$Sender
Contains the object that generated this event. This variable is
populated only within the Action block of an event registration command.
The value of this variable can also be found in the Sender property of
the PSEventArgs (System.Management.Automation.PSEventArgs) object that
Get-Event returns.

$ShellID
Contains the identifier of the current shell.

$SourceArgs
Contains objects that represent the event arguments of the event that
is being processed. This variable is populated only within the Action
block of an event registration command. The value of this variable
can also be found in the SourceArgs property of the PSEventArgs
(System.Management.Automation.PSEventArgs) object that Get-Event
returns.

$SourceEventArgs
Contains an object that represents the first event argument that derives
from EventArgs of the event that is being processed. This variable is
populated only within the Action block of an event registration command.
The value of this variable can also be found in the SourceArgs property
of the PSEventArgs (System.Management.Automation.PSEventArgs) object
that Get-Event returns.

$This
In a script block that defines a script property or script method, the
$This variable refers to the object that is being extended.

$True
Contains TRUE. You can use this variable to represent
TRUE in commands and scripts.

 

 

Ressources

 

Brandon Shell's blog

 

The $Error object

Error Handling Part 1

 

Trap exception

Error Handling Part 2

 

Set-PSDebug

Error Handling Part 3

 

 

Scripting Guys blog

 

http://blogs.technet.com/b/heyscriptingguy/archive/2009/07/13/hey-scripting-guy-how-can-i-handle-errors-in-a-windows-powershell-script.aspx

 

http://blogs.technet.com/b/heyscriptingguy/archive/2010/11/12/error-handling-and-exporting-active-directory-users-to-csv.aspx#Q3

 

http://blogs.technet.com/b/heyscriptingguy/archive/2010/03/08/hey-scripting-guy-march-8-2010.aspx

 

http://blogs.technet.com/b/heyscriptingguy/archive/2010/03/09/hey-scripting-guy-march-9-2010.aspx

 

http://blogs.technet.com/b/heyscriptingguy/archive/2010/03/10/hey-scripting-guy-march-10-2010.aspx

 

http://blogs.technet.com/b/heyscriptingguy/archive/2010/03/11/hey-scripting-guy-march-11-2010.aspx

 

 

MSDN on ErrorRecord

http://msdn.microsoft.com/en-us/library/system.management.automation.errorrecord.aspx

 

Design Guidelines for exceptions

http://msdn.microsoft.com/en-us/library/ms229014%28VS.80%29.aspx

(toutes les erreurs PowerShell sont des exceptions .Net)

 

Handling and throwing exceptions in .NET

http://msdn.microsoft.com/en-us/library/5b2yeyab.aspx

 

Introduction to exception handling in VB .NET

http://msdn.microsoft.com/en-us/library/aa289505.aspx

 

MSDN on Exception Handling

http://msdn.microsoft.com/en-us/library/ms229005.aspx

 

Exception handling fundamentals

http://msdn.microsoft.com/en-us/library/2w8f0bss.aspx

 

How to create a user-defined exception

http://msdn.microsoft.com/en-us/library/87cdya3t.aspx

 

Best practices for Exceptions Handling

http://msdn.microsoft.com/en-us/library/seyhszts.aspx

 

User-Filtered exceptions handlers

http://msdn.microsoft.com/en-us/library/4dy8x9k9.aspx

 

Handling and throwing exceptions

http://msdn.microsoft.com/en-us/library/5b2yeyab.aspx

 

Exception class and properties

http://msdn.microsoft.com/en-us/library/5whzhsd2.aspx

http://msdn.microsoft.com/en-us/library/system.exception.aspx

 

Exception hierarchy

http://msdn.microsoft.com/en-us/library/zbea8bay.aspx

 

ErrorAction and ErrorVariable

http://blogs.msdn.com/b/powershell/archive/2006/11/03/erroraction-and-errorvariable.aspx

 

 

Steven Murawski's blog

 

Error types

http://blog.usepowershell.com/2009/07/deep-dive-error-handling-error-types-part-1

 

 

Thomas Lee's blog

 

Error handling with PowerShell

http://tfl09.blogspot.com/2009/01/error-handling-with-powershell.html

 

 

PowerShell.com site

 

eBook on Finding and Avoiding Errors

http://powershell.com/cs/blogs/ebook/archive/2009/03/30/chapter-11-finding-and-avoiding-errors.aspx

(this is chapter 11 of a 567 pages free eBook document. A must)

 

 

tbs

 


 

IV - ERROR HANDLER EN ENVIRONNEMENT POWERSHELL

(page en cours de rédaction - translation pending, stay tuned)

 

 

http://technet.microsoft.com/en-us/library/dd938892%28SQL.100%29.aspx

 

Function Err_Handler {
  $err = "Error Category: " + $error[0].CategoryInfo.Category
  $err = $err + ". Error Object: " + $error[0].TargetObject
  $err = $err + " Error Message: " + $error[0].Exception.Message
  $err = $err + " Error Message: " + $error[0].FullyQualifiedErrorId
  $log = New-Object System.Diagnostics.EventLog('Application')
  $log.set_source("MyScript")
  $log.WriteEntry($err)
  }
Trap {
  # Handle the error
  Err_Handler
  # End the program.
  break;
  }

 

 

Ed Wilson on Error handling

 

 


 

V - JOURNALISATION DES ERREURS EN ENVIRONNEMENT POWERSHELL

(page en cours de rédaction - translation pending, stay tuned)

 

 

tbs

 


 

BONUS

(page en cours de rédaction - translation pending, stay tuned)

 

 

Trapping Errors

 

Vidéo.

 

 

Practical PowerShell

 

Vidéos.

 

 

Toutes les Cmdlets

 

Chez MSDN, c'est ici.

Chez TechNet, c'est plutôt .

 

 

Scripting with Windows PowerShell

 

Par ici.

 

 

Scriptomatic

 

PowerShell Scriptomatic

 

 

La doc

 

PowerShell vu par TechNet

 

PowerShell vu par MSDN

"The documents published here are written primarily for cmdlet, provider, and host application developers who require reference information about the APIs provided by Windows PowerShell." (Microsoft)
 
Windows PowerShell Getting Started Guide
Writing a Windows PowerShell Module
Writing a Windows PowerShell Cmdlet
Writing a Windows PowerShell Provider
Writing a Windows PowerShell Host Application
Windows PowerShell SDK

 

Scripts tirés du livre Windows PowerShell Cookbook par Lee Holmes

 

Ici.

 

 

 

Lister les évènements du log système des applications de ce jour

 

Exemple :

 

PS C:\Windows> $today = get-date 28/10/2010

PS C:\Windows> get-eventlog "application" -after $today

 

Résultat :

 

Index Time          EntryType   Source               InstanceID Message
----- ----          ---------   ------               ---------- -------
89890 oct. 28 18:26 Information Microsoft-Windows...       1000 Les compteurs de performances pour le service WmiApRpl (Wmi...
89889 oct. 28 18:26 Information Microsoft-Windows...       1001 Les compteurs de performances pour le service WmiApRpl (Wmi...
89888 oct. 28 15:57 Information VSS                        8224 Le service VSS s’arrête, car le délai d’inactivité est dépa...
89887 oct. 28 15:57 Information MsiInstaller               1033 Windows Installer a installé le produit. Nom du produit : W...
89886 oct. 28 15:57 Information MsiInstaller              11707 Product: WinZip 14.0 -- Installation operation completed su...
89885 oct. 28 15:56 Information Microsoft-Windows...      10001 Fin de session 0 avec démarrage 2010-10-28T13:52:39.3642578...
89884 oct. 28 15:56 Information MsiInstaller               1042 Fin d’une transaction Windows Installer : C:\Users\Didier\A...
89883 oct. 28 15:55 Information McLogEvent           1073746824 McShield service started....
89882 oct. 28 15:52 Information Microsoft-Windows...      10000 Début de session 0 - 2010-10-28T13:52:39.364257800Z.
89881 oct. 28 15:52 Information System Restore             8194 Point de restauration correctement créé (Processus = C:\Win...
89880 oct. 28 15:51 Information MsiInstaller               1040 Début d’une transaction Windows Installer : C:\Users\Didier...
89879 oct. 28 10:30 0 Software Protecti...           1073742727 Le service de protection logicielle s’est arrêté....
89878 oct. 28 10:25 0 Software Protecti...           1073742726 Le service de protection logicielle a démarré....
89877 oct. 28 10:25 Information Software Protecti... 1073742827 Le service de protection logicielle a terminé la vérificati...
89876 oct. 28 10:25 Information Software Protecti... 1073742857 Ces stratégies sont exclues, car elles ne sont définies qu’...
89875 oct. 28 10:25 Information Software Protecti... 1073742890 État d’initialisation pour les objets service....
89874 oct. 28 10:25 Information Software Protecti... 1073742724 Démarrage du service de protection logicielle....
89873 oct. 28 02:01 0 Microsoft-Windows...                  258 Le défragmenteur de disque a terminé défragmentation sur DA...
89872 oct. 28 02:00 0 Microsoft-Windows...                  258 Le défragmenteur de disque a terminé défragmentation sur BA...
89871 oct. 28 01:55 0 Microsoft-Windows...                  258 Le défragmenteur de disque a terminé défragmentation sur HP...
89870 oct. 28 01:36 Information Windows Error Rep...       1001 Récipient d’erreurs 809618590, type 5...
89869 oct. 28 01:36 Error Application Error                1000 Nom de l’application défaillante Explorer.EXE, version : 6....
89868 oct. 28 00:38 Error SideBySide                 3238068257 La création du contexte d’activation a échoué pour « C:\Pro...
89867 oct. 28 00:36 Error SideBySide                 3238068287 La création du contexte d’activation a échoué pour « C:\Pro...
89866 oct. 28 00:03 Information VSS                        8224 Le service VSS s’arrête, car le délai d’inactivité est dépa...

 

 

[début]


 

accueil | console | VBScript | PowerShell | documentation | formation  | trucs et astuces | exemples | glossaire