Powershell Write-Error不会填充-ErrorVariable

时间:2015-12-14 12:06:07

标签: powershell error-handling write-error

我正在运行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,我希望写入错误用$ output的内容填充变量$ myfuncerr,但这不会发生($ myfuncerr保持空白)。我在Powershell ISE中调试,所以我可以看到实际上调用了Write-Error。

我还尝试使用throw($ output)抛出异常,使用-ErrorAction运行myfunc SilentlyContinue,但仍未填充$ 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参数?

1 个答案:

答案 0 :(得分:2)

您需要通过提供# This is to determine which products belong to the same line # We can't just use product.id as you can have customised products # which should be treated as separate lines. Set as a # SlugField as it is included in the path for certain views. line_reference = models.SlugField(_("Line Reference"), max_length=128, db_index=True) product = models.ForeignKey( 'catalogue.Product', related_name='basket_lines', verbose_name=_("Product")) quantity = models.PositiveIntegerField(_('Quantity'), default=1) # We store the unit price incl tax of the product when it is first added to # the basket. This allows us to tell if a product has changed price since # a person first added it to their basket. price_excl_tax = models.DecimalField( _('Price excl. Tax'), decimal_places=2, max_digits=12, null=True) price_incl_tax = models.DecimalField( _('Price incl. Tax'), decimal_places=2, max_digits=12, null=True) # Track date of first addition date_created = models.DateTimeField(_("Date Created"), auto_now_add=True) 具有param()属性的块来表明您的功能是advanced function

[CmdletBinding()]

这会自动将common parameters添加到您的函数中,包括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 } } 参数