Search code examples
powershellerror-handlingwrite-error

Powershell Write-Error does not populate -ErrorVariable


I am running Powershell 4, and am trying to get an error variable to populate in a function by using the -ErrorVariable parameter in the call, and write-error within the function itself. However the variable never gets populated.

Here is my script:

$SqlCmd = "C:\Program Files\Microsoft SQL Server\110\Tools\Binn\SQLCMD.EXE"

myfunc -ErrorVariable myfuncerr 

if ($myfuncerr -and $myfuncerr.Count -ne 0) {
    $worked = 1
} else {
    $worked = 0
}

function myfunc 
{
    $output = & $SqlCmd -S localhost -d integration -q 'alter table tablethatdoesntexist add xt int' -b | out-string 

    if ($LASTEXITCODE = 1)
    {
        write-error $output
    }
}

Because it is the -ErrorVariable, I expect write-error to populate the variable $myfuncerr with the contents of $output, but this doesn't happen ($myfuncerr remains blank). I am debugging in Powershell ISE, so I can see that Write-Error is actually called.

I have also tried to throw an exception with throw($output), running myfunc with -ErrorAction SilentlyContinue, but still $myfuncerr is not populated, i.e

$SqlCmd = "C:\Program Files\Microsoft SQL Server\110\Tools\Binn\SQLCMD.EXE"

myfunc -ErrorVariable myfuncerr -ErrorAction SilentlyContinue

if ($myfuncerr -and $myfuncerr.Count -ne 0) {
    $worked = 1
} else {
    $worked = 0
}

function myfunc 
{
    $output = & $SqlCmd -S localhost -d integration -q 'alter table tablethatdoesntexist add xt int' -b | out-string 

    if ($LASTEXITCODE = 1)
    {
        throw $output
    }
}

Am I using the -ErrorVariable parameter correctly?


Solution

  • You need to indicate that your function is an advanced function by supplying a param() block with a [CmdletBinding()] attribute:

    function myfunc 
    {
        [CmdletBinding()]
        param()
    
        $output = & $SqlCmd -S localhost -d integration -q 'alter table tablethatdoesntexist add xt int' -b | out-string 
    
        if ($LASTEXITCODE -eq 1)
        {
            throw $output
        }
    }
    

    This will automatically add common parameters to your function, including the ErrorVariable parameter