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?

2
  • 1
    Possible duplicate of Emulating -ErrorAction in custom powershell function Commented Dec 14, 2015 at 12:33
  • Pretty sure you just need [CmdletBinding()] in order for your function to support those variables. Commented Dec 14, 2015 at 12:34

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.