2

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?

PRS
  • 741
  • 1
  • 7
  • 27
  • 1
    Possible duplicate of [Emulating -ErrorAction in custom powershell function](http://stackoverflow.com/questions/5950760/emulating-erroraction-in-custom-powershell-function) – Matt Dec 14 '15 at 12:33
  • Pretty sure you just need `[CmdletBinding()]` in order for your function to support those variables. – Matt Dec 14 '15 at 12:34

1 Answers1

3

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

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206