1

私は Powershell 4 を実行しており、呼び出しで -ErrorVariable パラメーターを使用し、関数自体で write-error を使用して、関数に入力するエラー変数を取得しようとしています。ただし、変数が設定されることはありません。

これが私のスクリプトです:

$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 が変数 $myfuncerr に $output の内容を入力することを期待していますが、これは起こりません ($myfuncerr は空白のままです)。Powershell ISE でデバッグしているので、実際に Write-Error が呼び出されていることがわかります。

-ErrorAction SilentlyContinue を指定して myfunc を実行し、throw($output) で例外をスローしようとしましたが、それでも $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 に答える