调用用户定义的函数时,无法在powershell中捕获非终止错误

时间:2017-07-30 17:21:47

标签: powershell powershell-v2.0 powershell-v3.0

我有一个用户定义的函数,它连接到数据库并执行查询,它将在循环中调用以在多个数据库上执行。如果数据库服务器报告了任何错误,则脚本会在控制台上报告错误。继续没有终止,这是预期的。但是,我想将该错误保存到变量&要么将其写入文件,要么将其保存到数据库中。

以下是示例代码:(不完整......)

function sqlCon($db, $sqlcmd)
{
    $connString = "Server='server_name';Database='$db';Integrated Security=sspi"
    $sqlConnect = New-Object System.Data.SqlClient.SqlConnection $connString
    $sqlConnect.Open()
    $sqlCommand = $sqlConnect.CreateCommand()
    $sqlCommand.CommandText = $sqlcmd
    $sqlCommand.ExecuteNonQuery() | Out-Null
    $sqlConnect.Close()      
    }
}

foreach($db in $databases){
   try{
    $sqlcmd = " use $($db);
          <<some sql query which updates or deletes>>"  
    sqlCon $db $sqlcmd
    #here i'm trying to catch non terminating errors but below statment never satisfies even 
    #i have errors while calling above function. Not sure if i'm missing anything here...
    if(-not($?)){
        throw "an error occured while executing query on $($db)."
    }   
       }
  catch{
    write-host "use this info to log into file or database." 
}
}

注意:我使用的是PowerShell V2,但PowerShell V3中的任何选项也适用于我。

1 个答案:

答案 0 :(得分:1)

-ErrorVariable功能添加CmdletBinding attribute并使用function sqlCon { [CmdletBinding()] param([string]$db, [string]$sqlcmd) # ... } foreach($db in $databases){ sqlCon -db $db -sqlcmd $sqlcmd -ErrorVariable sqlErrors if($sqlErrors.Count -gt 0){ # nonterminating errors were written, log items in $sqlErrors here } } 常用参数:

def myMethodA (param1, param2, specificParm)
    do code

 def myMethodB (param1, param2, specificParm1 specificParam2)
    do code