about_Throw

Aggiornamento: maggio 2014

Si applica a: Windows PowerShell 2.0, Windows PowerShell 3.0, Windows PowerShell 4.0, Windows PowerShell 5.0

ARGOMENTO

about_Throw

DESCRIZIONE BREVE

Descrive la parola chiave Throw, che genera un errore irreversibile.

DESCRIZIONE LUNGA

La parola chiave Throw causa un errore irreversibile. È possibile usare la parola chiave Throw per arrestare l'elaborazione di un comando, di una funzione o di uno script.

Ad esempio, è possibile usare la parola chiave Throw nel blocco di script di un'istruzione If per rispondere a una condizione o nel blocco Catch di un'istruzione Try-Catch-Finally. È anche possibile usare la parola chiave Throw in una dichiarazione di parametro per rendere un parametro della funzione obbligatorio.

La parola chiave Throw può generare qualsiasi oggetto, ad esempio una stringa con un messaggio per l'utente o l'oggetto che ha causato l'errore.

SINTASSI

La sintassi della parola chiave Throw è la seguente:

        throw [<expression>]

L'espressione nella sintassi Throw è facoltativa. Quando l'istruzione Throw non viene visualizzata in un blocco Catch e non include un'espressione, viene generato un errore ScriptHalted.

        C:\PS> throw

        ScriptHalted
        At line:1 char:6
        + throw <<<<
            + CategoryInfo          : OperationStopped: (:) [], RuntimeException
            + FullyQualifiedErrorId : ScriptHalted

Se la parola chiave Throw viene usata in un blocco Catch senza un'espressione, genera nuovamente l'oggetto RuntimeException corrente. Per altre informazioni, vedere about_Try_Catch_Finally.

GENERAZIONE DI UNA STRINGA

L'espressione facoltativa in un'istruzione Throw può essere una stringa, come illustrato nell'esempio seguente:

        C:\PS> throw "This is an error."

        This is an error.
        At line:1 char:6
        + throw <<<<  "This is an error."
            + CategoryInfo          : OperationStopped: (This is an error.:String) [], RuntimeException
            + FullyQualifiedErrorId : This is an error.

GENERAZIONE DI ALTRI OGGETTI

L'espressione può anche essere un oggetto che genera l'oggetto che rappresenta il processo di PowerShell, come illustrato nell'esempio seguente:Inserire qui il corpo del testo.

        C:\PS> throw (get-process PowerShell)

        System.Diagnostics.Process (PowerShell)
        At line:1 char:6
        + throw <<<<  (get-process PowerShell)
            + CategoryInfo          : OperationStopped: (System.Diagnostics.Process (PowerShell):Process) [], 
        RuntimeException
            + FullyQualifiedErrorId : System.Diagnostics.Process (PowerShell)

È possibile usare la proprietà TargetObject dell'oggetto ErrorRecord nella variabile automatica $error per esaminare l'errore.

        C:\PS> $error[0].targetobject

        Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName                                                            
        -------  ------    -----      ----- -----   ------     -- -----------                                                            
            319      26    61016      70864   568     3.28   5548 PowerShell

È anche possibile generare un oggetto ErrorRecord o un'eccezione di Microsoft .NET Framework. Nell'esempio seguente viene usata la parola chiave Throw per generare un oggetto System.FormatException.

        C:\PS> $formatError = new-object system.formatexception

        C:\PS> throw $formatError

        One of the identified items was in an invalid format.
        At line:1 char:6
        + throw <<<<  $formatError
            + CategoryInfo          : OperationStopped: (:) [], FormatException
            + FullyQualifiedErrorId : One of the identified items was in an invalid format.

ERRORE RISULTANTE

La parola chiave Throw può generare un oggetto ErrorRecord. La proprietà Exception dell'oggetto ErrorRecord contiene un oggetto RuntimeException. Il resto dell'oggetto ErrorRecord e l'oggetto RuntimeException variano con l'oggetto generato dalla parola chiave Throw.

L'oggetto RunTimeException viene sottoposto a inserito in un oggetto ErrorRecord e l'oggetto ErrorRecord viene automaticamente salvato nella variabile automatica $Error.

USO DI THROW PER CREARE UN PARAMETRO OBBLIGATORIO

È possibile usare la parola chiave Throw per rendere un parametro della funzione obbligatorio.

Si tratta di un'alternativa all'uso del parametro Mandatory della parola chiave Parameter. Quando si usa il parametro Mandatory, il sistema chiede all'utente il valore del parametro necessario. Quando si usa la parola chiave Throw, il comando si arresta e visualizza il record di errore.

Ad esempio, la parola chiave Throw nella sottoespressione del parametro rende il parametro Path un parametro obbligatorio nella funzione.

In questo caso, la parola chiave Throw genera una stringa di messaggio, ma è la presenza della parola chiave Throw che genera l'errore irreversibile se non viene specificato il parametro Path. L'espressione che segue Throw è facoltativa.

        function Get-XMLFiles
        {
            param ($path = $(throw "The Path parameter is required."))
            dir -path $path\*.xml -recurse | sort lastwritetime | ft lastwritetime, attributes, name  -auto
        }

VEDERE ANCHE

about_Break

about_Continue

about_Scope

about_Trap

about_Try_Catch_Finally