Simon Simon - 1 month ago 14
C# Question

Initialization failure when querying WMI-class Win32_ShadowCopy

while programming throughout the years I have never posted a question on this website, but I have encounted numerous of problems that had been addressed here before. Now, however, I encountered a problem that I can't seem to find an answer to.

I am creating an application in which I need information from the ShadowCopies on the system. I am trying to achieve this by using WMI (in C#). This is however giving me an "Initialization Failure"-exception.
Here's the code:
ManagementScope scope = new ManagementScope("\\.\ROOT\cimv2");

//create object query
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_ShadowCopy");

//create object searcher
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(scope, query);

//get collection of WMI objects
ManagementObjectCollection queryCollection = searcher.Get();

//enumerate the collection.
foreach (ManagementObject m in queryCollection)
{
// access properties of the WMI object
Console.WriteLine("ClientAccessible : {0}", m["ClientAccessible"]);

}


Whenever the foreach line is reached, a ManagementException is thrown with the message "Initialization Failure". I have absolutely no clue why this is happening. If I use the exact same code and change the WMI-class (to Win32_Processor/Win32_LogicalDisk/...) I am not getting this exception and the foreach-loop just works. I also noticed that the exception comes forth from the statement "searcher.Get();".
I have tried this code on a Windows Server 2008-machine as well as on a Windows 7 Enterprise-machine, both generating the same exception.

I have also tried using this class in a vb-script and that worked.
Code of VBS:

Set objWMIService = GetObject("winmgmts:\\" + ComputerName + "\root\cimv2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_ShadowCopy")

For Each objItem in colItems
Wscript.Echo objItem.ClientAccessible
Next


I am really clueless on what is generating this exception, especially since the WMI-class is working when I use a VB-script. Does anybody see what I am doing wrong here? Any help is appreciated and if you need more information to resolve this issue, just let me know!

Greetz,
Simon

//NOTE: I got this code from http://include.wutils.com/wmi/ROOT%5Ccimv2/CIM_ManagedSystemElement/CIM_LogicalElement/Win32_ShadowCopy/cs-samples.html

Answer

I had the same issue with a script I wrote that performs live WIM backups. Is the system you're running this on have UAC? If so, try either turning it off or running the app as Administrator - as soon as I did that it sprung to life.

Hope this helps