【问题标题】:How to actually unset (set to Nothing) COM-object property in Powershell?如何在 Powershell 中实际取消设置(设置为 Nothing)COM 对象属性?
【发布时间】:2018-03-27 10:21:47
【问题描述】:

我在将 this VBA/VB6 disconnected Recordset code 适应 Powershell 时遇到问题。设置为Nothing 翻译失败:

'disconnect the recordset and close the connection
Set rs.ActiveConnection = Nothing

第一次尝试(使用 $null):

$rs.ActiveConnection = $null

ERROR: Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another.
ERROR: + $rs.ActiveConnection = $null
ERROR: + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ERROR:     + CategoryInfo          : OperationStopped: (:) [], COMException
ERROR:     + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

第二次尝试(不执行设置为空):

$conn = new-Object -com "ADODB.Connection"
$rs = New-Object -ComObject "ADODB.Recordset"
$conn.ConnectionString = "Provider=SQLNCLI11;Server=myserver;Database=mydb;Integrated Security=SSPI;"
$conn.Open()
$rs.CursorLocation = 3 # adUseClient '<<<< important!
$rs.Open("select * from mytable where 1<>1", $conn, 2, 4) # adOpenDynamic, adLockBatchOptimistic
#$rs.ActiveConnection = $null
$conn.Close()
$rs.AddNew()
...
ERROR: Operation is not allowed when the object is closed.
ERROR: + $rs.AddNew()
ERROR: + ~~~~~~~~~~~~
ERROR:     + CategoryInfo          : OperationStopped: (:) [], COMException
ERROR:     + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

注意,我对 Invoke-SqlcmdADOROut-DataTable 等替代解决方案不感兴趣。我都试过了,不适合我的情况。

$PSVersionTable

Name                           Value                                                                                                                                                                                              
----                           -----                                                                                                                                                                                              
PSVersion                      5.1.14409.1012                                                                                                                                                                                     
PSEdition                      Desktop                                                                                                                                                                                            
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                                                                                                                            
BuildVersion                   10.0.14409.1012                                                                                                                                                                                    
CLRVersion                     4.0.30319.42000                                                                                                                                                                                    
WSManStackVersion              3.0                                                                                                                                                                                                
PSRemotingProtocolVersion      2.3                                                                                                                                                                                                
SerializationVersion           1.1.0.1      

这里的工作源代码供参考(它在 Excel 中使用 ADO 6.1 作为 VBA 工作):

Sub Tester()

    Dim con As ADODB.Connection, rs As ADODB.Recordset
    Dim i As Long

    Set con = getConn()

    Set rs = New ADODB.Recordset
    rs.CursorLocation = adUseClient '<<<< important!

    'get an empty recordset to add new records to
    rs.Open "select * from Table1 where false", con, _
             adOpenDynamic, adLockBatchOptimistic

    'disconnect the recordset and close the connection
    Set rs.ActiveConnection = Nothing
    con.Close
    Set con = Nothing

    'add some new records to our test recordset
    For i = 1 To 100
        rs.AddNew
        rs("UserName") = "Newuser_" & i
    Next i

    'reconnect to update
    Set con = getConn()
    Set rs.ActiveConnection = con

    rs.UpdateBatch '<<< transfer to DB happens here: no loop!

    rs.Close 

    'requery to demonstrate insert was successful
    rs.Open "select * from Table1", con, _
            adOpenDynamic, adLockBatchOptimistic

    Do While Not rs.EOF
        Debug.Print rs("ID").Value, rs("UserName").Value
        rs.MoveNext
    Loop

    rs.Close
    con.Close
End Sub

Function getConn() As ADODB.Connection
    Dim rv As New ADODB.Connection
    Dim strConn As String

    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" _
     & "Data Source = " & ThisWorkbook.Path & "\Test.accdb"

    rv.Open strConn
    Set getConn = rv
End Function

更新:最终工作代码(感谢下面的答案):

$ErrorActionPreference = 'Stop'
$src = Import-CSV -Path 'c:\mydata.csv'
$conn = new-Object -com "ADODB.Connection"
$rs = New-Object -ComObject "ADODB.Recordset"
$conn.ConnectionString = "Provider=SQLNCLI11;Server=myserver;Database=mydb;Integrated Security=SSPI;"
$conn.Open()
$rs.CursorLocation = 3 # adUseClient '<<<< important!

#get an empty recordset with fields defined
$rs.Open("select * from mytable where 1<>1", $conn, 2, 4) # adOpenDynamic, adLockBatchOptimistic

#
#disconnect the recordset
#

# Create a wrapper for the value null as per ZiggZagg's answer https://stackoverflow.com/a/49682554/2746150
[System.Runtime.InteropServices.UnknownWrapper]$nullWrapper = New-Object "System.Runtime.InteropServices.UnknownWrapper" -ArgumentList @($null);
# Get the the type for ADODB.Recordset as per ZiggZagg's answer https://stackoverflow.com/a/49682554/2746150
[Type]$recordSetType = [Type]::GetTypeFromProgID("ADODB.Recordset", $true);
# Write the property ActiveConnection as per ZiggZagg's answer https://stackoverflow.com/a/49682554/2746150
$recordSetType.InvokeMember([string]"ActiveConnection", [System.Reflection.BindingFlags]::SetProperty, [System.Reflection.Binder]$null, [object]$rs, [object[]]@($nullWrapper));
# Close connection
$conn.Close()

#fillup code
Foreach ($row in $src) {
    $rs.AddNew()
    Foreach ($col in $row.psobject.Properties.Name) {
        $fld = $rs.Fields.Item($col)
        $fld.Value = $row.$col
    }
}

#reconnect
$conn.Open()
$rs.ActiveConnection = $conn

#final update
$rs.UpdateBatch()
$rs.Close()

此代码用于批量加载 10K-50K 行,其中包含 100 多个字段(可变)。类似的代码using Out-DataTable 的行数增加了十倍(因为每个字段都必须定义)并且具有相似的性能。

【问题讨论】:

  • 你的代码没有意义。您正在关闭连接,然后尝试调用AddNew。反过来做就好了。
  • @DavidG,它是关于 disconnected 记录集的。是的,反过来。首先关闭连接,然后调用 AddNew。
  • 有趣的东西。 $Null 应该可以工作,但 PowerShell 绑定器显然不能正确处理这种情况——无论出于何种原因。到目前为止,阻力最小的方法是保持此代码原样并使用cscript 运行它,或者使用 ADO.NET 而不是经典 ADO 迁移到任何东西。但确实应该在 PowerShell 本身中提供解决方案。
  • @Jeroen Mostert,我尝试了 $conn.Close()Clear-Variable conn[Runtime.InteropServices.Marshal]::ReleaseComObject($rs.ActiveConnection) 的各种组合 - 不走运。确实应该有一个PS解决方案。我怀疑 ActiveConnection 的属性设置器中有一些代码在 Nothing 进入时将记录集标记为“断开连接”。
  • @AntonKrouglov 忘记了断开连接的记录集。它们在 15 年前被数据集取代,这些数据集在定义上是断开的。 Powershell 是 .NET。您应该使用 ADO.NET 类。更好的是,使用 SQL Server modulescommands,例如:Invoke-Sqlcmd -InputFile "C:\ScriptFolder\TestSqlCmd.sql" | Out-File -FilePath "C:\ScriptFolder\TestSqlCmd.rpt"

标签: sql-server powershell ado


【解决方案1】:

我不得不承认我不确定以下是否与您的 VBA 脚本相同。您介意检查一下它是否符合您的预期吗?

# Create a wrapper for the value null
[System.Runtime.InteropServices.UnknownWrapper]$nullWrapper = New-Object "System.Runtime.InteropServices.UnknownWrapper" -ArgumentList @($null);
# Get the the type for ADODB.Recordset
[Type]$recordSetType = [Type]::GetTypeFromProgID("ADODB.Recordset", $true);
# Write the property ActiveConnection
$recordSetType.InvokeMember([string]"ActiveConnection", [System.Reflection.BindingFlags]::SetProperty, [System.Reflection.Binder]$null, [object]$rs, [object[]]@($nullWrapper));

【讨论】:

  • 谢谢 - 它成功了。只需要添加一些小怪癖 - 请参阅问题中的更新。
猜你喜欢
  • 1970-01-01
  • 2014-05-02
  • 1970-01-01
  • 1970-01-01
  • 2011-02-05
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
  • 2011-09-24
相关资源
最近更新 更多