1

我正在运行 Powershell 4,并试图通过在调用中使用 -ErrorVariable 参数并在函数本身中写入错误来获取错误变量以填充到函数中。但是,该变量永远不会被填充。

这是我的脚本:

$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
    }
}

因为它是 -ErrorVariable,所以我希望 write-error 用 $output 的内容填充变量 $myfuncerr,但这不会发生($myfuncerr 保持空白)。我在 Powershell ISE 中调试,所以我可以看到 Write-Error 实际上被调用了。

我还尝试使用 throw($output) 抛出异常,使用 -ErrorAction SilentlyContinue 运行 myfunc,但仍然没有填充 $myfuncerr,即

$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
    }
}

我是否正确使用了 -ErrorVariable 参数?

4

1 回答 1

2

您需要通过提供具有属性的块来表明您的功能是高级功能:param()[CmdletBinding()]

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
    }
}

这会自动将常用参数添加到您的函数中,包括ErrorVariable参数

于 2015-12-14T12:38:00.487 回答