A while ago I posted about how to use WMI associations when scripting Hyper-V in order to increase the efficiency of your scripts. Today I would like to provide some new information – and some clarifications in response to questions that I have received.
First – in the original post I showed you how to get a virtual network adapter under PowerShell by looking at the WMI association; like this:
It turns out there is an easier way to do this in PowerShell v2.0 – by using the “GetRelated” command. So you can just do this:
Here you just pass the desired result class as a parameter – and GetRelated will do all the work for you.
Next – I would like to spend a moment to answer some questions I have received about the efficiency of using associations versus getting all objects and filtering. I have had a couple of people contact me asking why some of their scripts are faster when using associations, while others are slower. The key question to always keep in mind is “which approach will return the smallest number of WMI objects”.
For example: in my “attach an .ISO file” script I get all the virtual machines, find the virtual machine I want and then use the WMI associations to get the DVD drive. I could have just got all the DVD drives on the system and filtered out the ones I did not want – but in most cases there are at least as many DVD drives as there are virtual machines, and there can be cases where there are more DVD drives than virtual machines. So using associations will usually return fewer WMI objects – in this case.
However, in my lightweight virtual machine inventory script (the second one in the article) I do not use associations – and instead I get all of the KVP objects on the system. The reason why I do this is because I want to display information from all of the KVP objects – and I will not be filtering the results. If I had got all of the virtual machine objects and walked the associations on each one – I would have doubled the number of WMI objects I was working with – and had a much slower script.
I hope that helps some people out – and as always – feel free to ask questions!