ManagementObjectSearcher will fail in some conditions

StewartBW 585 Reputation points
2024-04-06T17:08:39.6933333+00:00

Hello

I use this code to get some hardware info, ie MyQuery("BusType") etc:

Using MySearcher As New ManagementObjectSearcher("root\Microsoft\Windows\Storage", "SELECT * FROM MSFT_PhysicalDisk WHERE DeviceId = 1")
Using MyQuery As ManagementObject = TryCast(MySearcher.Get(0), ManagementObject)

If I disable the Winmgmt service, and enable + start it back, the above code will not work for some time (usually a few minutes) and MyQuery will be null.

Is my code correct and what causes this?

The problem is that in some cases, the same thing will also happen.

I don't get why when this happens, I can run this code and it will work:

Using Search As New ManagementObjectSearcher(New SelectQuery("Win32_Processor"))
For Each Info As ManagementObject In Search.Get
Info("Manufacturer")...

But the above first code will not!

Thank you

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,457 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,620 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 27,501 Reputation points Microsoft Vendor
    2024-04-09T09:05:06.27+00:00

    Hi @StewartBW ,

    When you stop and restart the WMI service, it might take some time for it to initialize fully and start providing accurate information again. During this initialization period, your code may not be able to retrieve the expected data.

    You can try using loops with a delay to retry until the query returns a result.

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Castorix31 82,241 Reputation points
    2024-04-07T08:09:18.3733333+00:00

    I noticed the same thing on my PC (Windows 10 22H2) by doing tests with WMI Code Creator

    But for physical disk, you should use Win32_DiskDrive