Powershell Write-Error 不填充 -ErrorVariable
Powershell Write-Error does not populate -ErrorVariable
我是 运行 Powershell 4,我试图通过在调用中使用 -ErrorVariable 参数并在函数本身内写入错误来获取错误变量以填充到函数中。但是,该变量永远不会被填充。
这是我的脚本:
$SqlCmd = "C:\Program Files\Microsoft SQL Server0\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) 抛出异常,运行 myfunc 和 -ErrorAction SilentlyContinue,但仍然没有填充 $myfuncerr,即
$SqlCmd = "C:\Program Files\Microsoft SQL Server0\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 参数?
您需要通过提供具有 [CmdletBinding()]
属性的 param()
块来表明您的函数是 advanced function:
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
}
}
这会自动将 common parameters 添加到您的函数中,包括 ErrorVariable
参数
我是 运行 Powershell 4,我试图通过在调用中使用 -ErrorVariable 参数并在函数本身内写入错误来获取错误变量以填充到函数中。但是,该变量永远不会被填充。
这是我的脚本:
$SqlCmd = "C:\Program Files\Microsoft SQL Server0\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) 抛出异常,运行 myfunc 和 -ErrorAction SilentlyContinue,但仍然没有填充 $myfuncerr,即
$SqlCmd = "C:\Program Files\Microsoft SQL Server0\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 参数?
您需要通过提供具有 [CmdletBinding()]
属性的 param()
块来表明您的函数是 advanced function:
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
}
}
这会自动将 common parameters 添加到您的函数中,包括 ErrorVariable
参数