Exception calling "GetOwner"

364 Views Asked by At

team! Recently, my remote pssession scripts has failed under getting owner of processes.

        #Some code up and down the fragmet
        #Use WMI or CIM cmdlets.
        $UseCIM = !( Test-GetWMIObjectPresent ) #local function to choose CIM or WMI methods 
        if ( $UseCIM ) {
            $ProcessArray = Get-CimInstance -ClassName 'Win32_Process' -Property  $ProcessProperties                       
        }
        Else {
            $ProcessArray = Get-WmiObject  -Class 'Win32_Process' -Property  $ProcessProperties 
        }

        $ProcessArray | Add-Member -NotePropertyName 'User' -NotePropertyValue ''
        $ProcessProperties += 'User'
        $ProcessArray | Add-Member -NotePropertyName 'ComputerName' -NotePropertyValue $env:COMPUTERNAME
        $ProcessProperties += 'ComputerName'

        foreach ( $Item in $ProcessArray ){
            try {
                if (  $UseCIM ) {
                    # We have error here!!!
                    $Owner = $Item | Invoke-CimMethod -MethodName 'GetOwner' -ErrorAction 'SilentlyContinue'
                }
                Else {
                    # and here!
                    $Owner = $Item | Invoke-WmiMethod -Name 'GetOwner' -ErrorAction 'SilentlyContinue'
                }
                if ( $Owner ){
                    if ( $Owner.domain ){
                        $Item.User = "$( $Owner.domain )\$( $Owner.User )"
                    }
                    Else {
                        $Item.User = "$( $Owner.User )"
                    }
                }
            }
            Catch{
                Add-ToLog -Message "$_" -Display -Status "error"
            }
        }

Remote user has administrative rights.

We have error:

Exception calling "GetOwner" : "Operation is not valid due to the current state of the object."

if we run it under local session, no errors happens. Any suggestions?

1

There are 1 best solutions below

0
On

To get the owner, the object on that you pass to GetOwner must have a property named Handle.

From the docs:

The object returned also contains the key properties even if you have not listed them using the Property parameter. Other properties of the class are present but they are not populated.

Credit to Theo in the comments