none
PowerShell Trap statement scope in Script Block RRS feed

  • Question

  • The documentation for the PowerShell Trap statement here:

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

    indicates that Trap statements can return execution to the statement after the one that raised the error, if it is in the same scope. This is not correct, unless you define a script block as a separate scope. The following PowerShell script demonstrates:

     

    Trap {"Error 1: $_"; Continue}

    $Name = "administrator"
    $Computer = "MyComputer"
    $User = [ADSI]"WinNT://$Computer/$Name,user"
    If ($user.Name -ne $Null)
    {
        # Trap {"Error 2: $_"; Continue}
        "Step 1"
        "$Name found"

        $Attr = "Description"
        $Value = ""
        $Value = $User.Get($Attr)
        "$Attr = $Value"

        $Attr = "FullNamex"
        $Value = ""
        "Step 2"
        $Value = $User.Get($Attr)
        "Step 3"
        "$Attr = $Value"

        "Step 4"
        $Attr = "Name"
        $Value = ""
        $Value = $User.Get($Attr)
        "$Attr = $Value"
    }
    "Step 5"
    $Attr = "FullNamex"
    $Value = ""
    $Value = $User.Get($Attr)
    "$Attr = $Value"

    $Attr = "Name"
    $Value = ""
    $Value = $User.Get($Attr)
    "$Attr = $Value"

    -----

     

    As written (assuming valid values for computer and user), the script skips "Step 3" and "Step 4". After the error attempting to retrieve "FullNamex" in the script block, the next statement to execute is "Step 5", after the script block. The script successfully retrieves the "Name" attribute at the end of the script. However, if you uncomment the second Trap statement, which is in the script block, all statements run. I conclude that script blocks (in If statements for example) are different scopes for the Trap statement.

     


    Richard Mueller - MVP Directory Services
    Tuesday, September 6, 2011 4:12 PM