通过Powershell调用存储过程时如何检索OUTPUT语句

发布于 2024-12-09 21:17:58 字数 835 浏览 1 评论 0原文

我正在 powershell 中运行以下脚本,但是我似乎无法检索任何 PRINT 语句或错误消息?请问如何捕获 powershell 会话中的所有输出?

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$sql_server;Database=$sql_db;user ID=$sql_usr;password=$sql_pwd"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.Connection = $SqlConnection
$SqlCmd.CommandText = "$storedProc"
$SqlCmd.CommandType = [System.Data.CommandType]::StoredProcedure
$SqlCmd.Parameters.Add("@COBDate", "$dateVariable")
$handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] {param($sender, $event) Write-Host $event.Message }; 
$SqlConnection.add_InfoMessage($handler); 
$SqlConnection.FireInfoMessageEventOnUserErrors = $true;
$SqlConnection.Open()
$SqlCmd.ExecuteNonQuery()
$SqlCmd.Parameters.value
$SqlConnection.Close()

I am running the following script in powershell, however I don't seem to be able to retrieve any PRINT statements or error messages? How do I capture all outputs within the powershell session please?

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$sql_server;Database=$sql_db;user ID=$sql_usr;password=$sql_pwd"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.Connection = $SqlConnection
$SqlCmd.CommandText = "$storedProc"
$SqlCmd.CommandType = [System.Data.CommandType]::StoredProcedure
$SqlCmd.Parameters.Add("@COBDate", "$dateVariable")
$handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] {param($sender, $event) Write-Host $event.Message }; 
$SqlConnection.add_InfoMessage($handler); 
$SqlConnection.FireInfoMessageEventOnUserErrors = $true;
$SqlConnection.Open()
$SqlCmd.ExecuteNonQuery()
$SqlCmd.Parameters.value
$SqlConnection.Close()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南薇 2024-12-16 21:17:58

我实现Eventhandler的方式如下:

#Method 1 use hidden method
$Sqlconnection.FireInfoMessageEventOnUserErrors=$true
#...
$handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] {Write-Host "$($_)"}
$Sqlconnection.add_InfoMessage($handler)
#OR Method 2 use Register-ObjecEvent
Register-ObjectEvent -InputObject $SqlConnection-EventName InfoMessage -Action { Write-Host " $($Event.SourceEventArgs)" } -SupportEvent
#...
$SqlConnection.Open()

The way I've implemented Eventhandler is as follows:

#Method 1 use hidden method
$Sqlconnection.FireInfoMessageEventOnUserErrors=$true
#...
$handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] {Write-Host "$($_)"}
$Sqlconnection.add_InfoMessage($handler)
#OR Method 2 use Register-ObjecEvent
Register-ObjectEvent -InputObject $SqlConnection-EventName InfoMessage -Action { Write-Host " $($Event.SourceEventArgs)" } -SupportEvent
#...
$SqlConnection.Open()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文