What do you mean by ‘doesn’t work’? Do you get any error messages?
How are you defining $service? That’s not included in your code.
What version of PowerShell are you using? WMI cmdlets are not available in PowerShell, only Windows PowerShell (you should be using Get-CIMInstance in both).
Please provide your full code and error messages, formatted as code (see below), and maybe we can get to the bottom of it.