Use PowerShell to wrap an existing COM object

前端 未结 2 1678
死守一世寂寞
死守一世寂寞 2020-12-16 03:17

Using PowerShell and System.DirectoryServices, I\'ve been given an object that looks like this:

   TypeName: System.__ComObject

Name                    


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 04:05

    Just a little different approach then Bill Stewart’s:

    The idea is that usually you do not need/want to create multiple instances of the ComObject:

    Function Invoke-ComObject([Parameter(Mandatory = $true)]$ComObject, [Switch]$Method, [Parameter(Mandatory = $true)][String]$Property, $Value) {
        If ($ComObject -IsNot "__ComObject") {
            If (!$ComInvoke) {$Global:ComInvoke = @{}}
            If (!$ComInvoke.$ComObject) {$ComInvoke.$ComObject = New-Object -ComObject $ComObject}
            $ComObject = $ComInvoke.$ComObject
        }
        If ($Method) {$Invoke = "InvokeMethod"} ElseIf ($MyInvocation.BoundParameters.ContainsKey("Value")) {$Invoke = "SetProperty"} Else {$Invoke = "GetProperty"}
        [__ComObject].InvokeMember($Property, $Invoke, $Null, $ComObject, $Value)
    }; Set-Alias ComInvoke Invoke-ComObject
    

    If it concerns a method, you need to add the –Method switch, in the case of a property, the cmdlet will automatically determine whether the property need to be get or set depending on whether a value is supplied. With this cmdlet you do not require the to create the ComObject first and retrieve e.g. to get the ComputerName (DN) from ADSystemInfo in a simple oneliner:

    ComInvoke ADSystemInfo ComputerName
    

    To do a the same with the PathName:

    $EscapedMode = ComInvoke PathName EscapedMode
    ComInvoke PathName EscapedMode @($ADS_ESCAPEDMODE_ON)
    ComInvoke Pathname -Method Set @("CN=Ken Dyer,OU=H/R,DC=fabrikam,DC=com", $ADS_SETTYPE_DN)
    ComInvoke Pathname -Method Retrieve @($ADS_FORMAT_X500_PARENT)
    ComInvoke PathName EscapedMode @($EscapedMode)
    

    A name NameTranslate example:

    ComInvoke -Method NameTranslate Init @(1, "domain.com")
    ComInvoke -Method NameTranslate Set @(8, "User001")
    ComInvoke -Method NameTranslate Get @(1)
    

    Or if you do want to have multiple instances you can first create the ComObject instance and then supply it to the ComInvoke function:

    $NameTranslate = New-Object -ComObject NameTranslate
    ComInvoke -Method $NameTranslate Init @(1, "domain.com")
    ComInvoke -Method $NameTranslate Set @(8, "User001")
    ComInvoke -Method $NameTranslate Get @(1)
    

    For the latest Invoke-ComObject version, see: https://powersnippets.com/invoke-comobject/

提交回复
热议问题