我已经处理了一段时间了。我有一个简单的powershell函数,它接受到SQL服务器的开放连接和包含SQL命令的字符串,并在服务器上运行它。函数应返回一个整数值,表示已更新的行数。但是,它却输出有关该方法的信息。
代码:
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)
}
但是,在执行时,我得到以下错误:
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
我知道
ExecuteNonQuery
,当管道输送到
Out-String
,正在输出具有其重载定义的表:
OverloadDefinitions
-------------------
int ExecuteNonQuery()
int IDbCommand.ExecuteNonQuery()
我也尝试过不将其管道化到任何对象,这样在没有表头的情况下返回了类似的结果。
编辑:另外,我应该提到,我95%确信sql命令执行成功。我肯定这个函数以前工作过一次,甚至返回正确的输出。然而,这种情况已经不长时间了。
我的问题是:
-
为什么?
-
如何让它输出受影响的行数?