Get-windowskey is a function I have loaded into my environment which takes the name of a pc, stated with the param -targets, and returns the Windows version and product key. When I run the above script with hard coded $Computers, it runs great. However, running the above gives me the below error, any advice?
Thanks in advance
Cannot convert value "\\CAND8TQ14J\root\default:stdRegProv" to type "System.Management.ManagementClass". Error: "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)"
At C:\Powershell\GetProductKeyFunction.ps1:11 char:9
+ $wmi = [WMIClass]"\\$target\root\default:stdRegProv"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastToWMIClass
You cannot call a method on a null-valued expression.
At C:\Powershell\GetProductKeyFunction.ps1:12 char:9
Your ForEach-Object is a bit of an odd way to do what you’re after…
Get-ADComputer -filter * | Select -Expand Name
Is a bit more common.
The errors are coming from inside your Get-WindowsKey function. Without seeing it, it’s a bit difficult to guess what might be wrong. But, the error “RPC server is unavailable” suggests that it isn’t connecting to the computer listed in $target.
I suspect you might be able to query the same info more easily by using the Win32_OperatingSystem class, too. That’d eliminate needing to mess with the registry, if the info you need is in there.
Looks like all you really need is some error handling. If the ([WMIClass]“\$target\root\default:stdRegProv”) expression throws an error such as RPC Server is Unavailable, there’s really no point in trying to run the rest of the code for that particular target.
Just to give an update, I managed to get it working. I changed the param for the function to except get-content, and added some error handling. Working out the rest of the kinks, but pretty happy with what I have so far. Thanks to you both for pointing me in the right direction.