SqlClient.ExecuteNonQuery不返回行数

Mas*_*all 2 powershell return-type sqlclient

我一直在处理这个问题.我有一个简单的PowerShell函数,它接受SQL Server的开放连接和包含SQL命令的String,并对服务器运行它.该函数应返回一个整数值,表示已更新的行数.但是,它正在输出有关该方法的信息.

码:

function Invoke-MSSQLNonQuery () {
    param (
        [System.Data.SqlClient.SqlConnection]$Connection,
        [string]$Command
    )

    # Create the SQL Command Ojbect
    $SQLCommand = New-Object System.Data.SqlClient.SqlCommand

    # Set the Command Text and Connection for the Command
    $SQLCommand.CommandText=$Command
    $SQLCommand.Connection=$Connection

    # Run command and return the rows affected
    [int]($SQLCommand.ExecuteNonQuery | Out-String)
}
Run Code Online (Sandbox Code Playgroud)

但是,执行时,我收到以下错误:

Cannot convert value "
OverloadDefinitions
-------------------
int ExecuteNonQuery()
int IDbCommand.ExecuteNonQuery()

" to type "System.Int32". Error: "Input string was not in a correct format."
At C:\_Local\playground\Mason\UpdateFromInventory.ps1:153 char:5
+     [int]($SQLCommand.ExecuteNonQuery | Out-String)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastFromStringToInteger
Run Code Online (Sandbox Code Playgroud)

我知道ExecuteNonQuery,当用管道Out-String输出时,输出一个带有超载定义的表:

OverloadDefinitions
------------------- 
int ExecuteNonQuery() 
int IDbCommand.ExecuteNonQuery()
Run Code Online (Sandbox Code Playgroud)

我也试过不管它到任何东西,它返回一个没有表头的类似结果.

编辑:另外,我应该提到我95%确定SQL命令正在成功执行.我确信这个功能之前已经工作过一次,甚至返回正确的输出.然而,长期以来并非如此.

我的问题是:

  1. 为什么?
  2. 如何让它输出受影响的行数呢?

Ans*_*ers 6

您正在尝试调用没有括号的方法.这样做时,语句将显示一个重载列表(例如,参见此处),而不是实际调用该方法,即使您首先将其转换为字符串,也不能将其转换为整数.

更改

[int]($SQLCommand.ExecuteNonQuery | Out-String)
Run Code Online (Sandbox Code Playgroud)

[int]$SQLCommand.ExecuteNonQuery()
Run Code Online (Sandbox Code Playgroud)

并且代码应该做你想要的.