2017-07-30 8 views
0

データベースに接続してクエリを実行するユーザー定義関数があります。複数のデータベースで実行するためにループで呼び出されます。データベースサーバーによってエラーが報告された場合、スクリプトはコンソールでエラーを報告します。&は、終了することなく予想されます。しかし、そのエラーを変数&に保存するか、ファイルに書き込むか、データベースに保存してください。 (...その完全ではない)ユーザ定義関数を呼び出すときにpowershellで終了しないエラーをキャッチできません

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が、V3も私の作品PowerShellのいずれかのオプションを使用しています。

答えて

1

CmdletBinding attributesqlCon機能を追加し、-ErrorVariable共通パラメータを使用します。

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

完璧な実用的なソリューションを...ありがとう:) – sqlcheckpoint

関連する問題