Question

Salutations!

So, I was just on my daily routine of some powershell programming and I got to this little fella:

Get-WmiObject : Invalid class 
At line:184 char:19
+ $RECApp = gwmi <<<<  Win32_product | ? {$_.Name.Contains($Application)}
+ CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErrorId: GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

The funny thing is that this error is only shown when the code is executed from a script, but when manually entered into the command line the same code works. I don't know if this has something to do with the remote machine which I'm executing the script on, but why should it, if it works when entered manually but not when executed from the script. I'll get you a piece of my code here:

Enter-PSSession -ComputerName $serverName
$App = gwmi Win32_product | ? {$_.Name.Contains($Application)}
$App.Uninstall();
exit

To summarize, why does this code work like a charm when entered manually to the command line, but when executed form a script I get the above error?

Thanks.

Was it helpful?

Solution

Enter-PSSession is for interactive use only. If you put that line in a script, the subsequent lines do not run in a remote session. If you want to run some script remotely, within a script, you would do something like this instead:

$session = New-PSSession -ComputerName $serverName
Invoke-Command -Session $session {
    param($name)

    $App = gwmi Win32_product | ? {$_.Name.Contains($name)}
    $App.Uninstall();
} -arguments $application

There's a bit of a gotcha there as I have to pass $application as an argument to Invoke-Command because that variable does not exist on the remote session. Stepping back a bit, you could write the above a bit simpler like this:

$app = gwmi -computer $servername win32_product | ? {
      $_.name.contains($application)
}

Now, the problem with this is that you are pulling all win32_product objects back from the server and filtering on the local machine. This is a lot of unneccessary network traffic. It would be faster if you could filter on the remote machine, so let's modify it a bit more:

$app = gwmi -computer $servername -query `
    "select * from win32_product where name = '$application'"
$app.Uninstall()

Now only the win32_product you want will be retrieved from the remote machine. I haven't tested the above gwmi -computer variants, so it's more illustrative of technique and syntax. You may have to play a bit with it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top