Product get name ошибка

  • Remove From My Forums
  • Вопрос

  • Windows 2003 Server Standard Edition SP2. Только что переустановил, никакого другого софта еще не установлено. При запуске из консоли wmic product get name выдается ошибка:

    Узел — имя_компьютера

    ОШИБКА:

    Код = 0x80041010

    Описание = Недопустимый класс

    Услуга WMI

    Службы WMI запущены и функционируют нормально. На другие параметры wmic откликается а вот на wmic product не хочет. Может кто нибудь знает как это лечится? при поиске данной ошибки заметил, что у многих не работает в указанной ОС.

Ответы

  • а погуглить не судьба?

    доустановите компоненту WMI Windows Installer Provider (AddRemove Programs -> AddRemove Windows components -> Management and Monitoring tools)

    ——————————

    проверил — работает

    C:Documents and SettingsAdministrator>wmic product
    Node — DHCPSRV
    ERROR:
    Code = 0x80041010
    Description = Invalid class
    Facility = WMI

    C:Documents and SettingsAdministrator>wmic product
    Caption                                      Description
    VMware Tools                                 VMware Tools
    Microsoft .NET Framework 2.0 Service Pack 1  Microsoft .NET Fram
    Microsoft File Server Migration Toolkit      Microsoft File Serv
    Windows Support Tools                        Windows Support Too

    • Помечено в качестве ответа

      15 сентября 2010 г. 9:14

Try

This is not a full list (wmic). This is only products installed with Windows Installer. There is no feature for everything.

However as I said in my previous post nearly everything is listed in the registry.

So to see it in a command prompt

reg query HKLMSOFTWAREMicrosoftWindowsCurrentVersionUninstall /s

Also your error code seems invalid. There is no 27a windows error or 0xc000027a NT Status code. It seems wrong for a COM containing NTSTatus 0xd000027a or COM with Windows error 0x8007027a.

Clean Booting

Each of the three steps turns of programs, services, and drivers in increasing amounts. Thus narrowing down the possible culprits.

Clean Boot

Click Start — All Programs — Accessories — Run and type

msconfig

Then go to the Startup tab. Untick everything. Then go to the Services tab. Tick Hide All Microsoft Services and untick everything that’s left.

Reboot. If this solves your problem reenable ½ of the services/startup items until you find which one.

Advanced Clean Boot

If the above doesn’t help.

Download Autoruns from http://technet.microsoft.com/en-us/sysinternals/bb963902.aspx

Start the program by right clicking and choosing Run As Administrator and click Options menu — Filter Options and tick Hide Microsoft entries and clear Include Empty Locations. Untick everything left.

Reboot. If this solves your problem reenable ½ of the items until you find which one.

Safe Mode

If the above doesn’t help.

Use Safe Mode with Networking if you need internet access.

Click Start — All Programs — Accessories — Run and type

msconfig

Then go to the Boot tab and click Safe Boot (also tick Network if needed). Reboot. Come back here and untick Safe Boot to return to normal mode.

or

If your computer has a single operating system installed, repeatedly press the F8 key as your computer restarts. You need to press F8 before the Windows logo appears. If the Windows logo appears, you will need to try again. [From Start — Help and Support]

Startup Repair

If your computer has a single operating system installed, repeatedly press the F8 key as your computer restarts. You need to press F8 before the Windows logo appears. If the Windows logo appears, you will need to try again. [From Start — Help and Support].

On the Advanced Boot Options screen, use the arrow keys to highlight Repair your computer, and then press ENTER.

Select Startup Repair.

Startup repair makes a log file. See C:WindowsSystem32LogFilesSrtSrtTrail.txt.

To access if Windows won’t start, on the Advanced Boot Options screen, use the arrow keys to highlight Repair your computer, and then press ENTER.

Select Command Prompt.

Type

type C:WindowsSystem32LogFilesSrtSrtTrail.txt |more

Also type explorer in your command prompt and see what happens.

My Explorer fixes listsways of using windows without the graphical shell.

To See if a Fix is Available

In Control Panel (and select Classic view in the left hand pane) choose Problem Reports and Solutions (type problem in Start’s search box), go to Problem History, right click your error and choose Check For Solution.

You may also right click and choose Details for more info. Post those details here. The Fault Module Name is the important information.

If the problem affects Control Panel press Winkey + R and type wercon (or type it in a command prompt).


Close Explorer and Start a Command Prompt

Close any Explorer windows

Start — All Programs — Accessories — Right click Command Prompt and choose Run As Administrator.

Click Start. Ctrl + Shift + Right click a blank spot (just above the power buttons is one place) then Exit Explorer.

Press Ctrl + Alt + Delete then Task Manager.

Check all explorer processes are closed. On the Process tab select explorer and right click and choose End Process, repeat if more than one explorer in the list.

Then to restart explorer after trying each of the following

Press Ctrl + Alt + Delete and choose Task Manager

In Task Manager click the File menu then New Task (Run) and type explorer


If You Can’t Start Explorer at All

Press Ctrl + Alt + Delete and choose Task Manager

On the Process tab click Show Processes From All Users to elevate to Administrator
In Task Manager click the File menu then New Task (Run) and type cmd
Other things you can try typing

Explorer
Explorer c:
Explorer /e,c:
wercon
control
iexplore
rstrui

If you can’t start a folder window use the Browse button in the New Task dialog. Remember you need to right click and choose Open rather than double clicking.


There are many ways to automate (un)installation of MSIs, WMIC being one of them. Have you thought about a simpler approach, like a batch file that does:

rem Uninstall old program:
msiexec /qb /x {05EC21B8-4593-3037-A781-A6B5AFFCB19D}
rem Install new program:
msiexec /qb /i MyNewProgram.msi

(of course, replacing the GUID above with your program’s GUID or Uninstall key name).

Or, you could use the Automation interface to the Windows Installer.

Or, you could use WMI via VBScript or PowerShell to accomplish the same thing as WMIC will do. But it looks like WMI might be a bit hosed.

I don’t have a fix for what I’m seeing, but I do have a couple of things you can try. I recently spent a bit of time troubleshooting WMI issues, so maybe a couple of those same techniques will work here.

First, here is a VBScript that should output the same thing as product get name. Save it to a file getProductNames.vbs and execute it.

Option Explicit

Dim strComputer
Dim objWMIService, colProducts, objProduct
Dim arrstrProducts(), i

strComputer = "."
Set objWMIService = GetObject("winmgmts:\" & strComputer & "rootcimv2")
Set colProducts = objWMIService.ExecQuery("Select * From Win32_Product")

i = 0
For Each objProduct in colProducts
    ReDim Preserve arrStrProducts(i)
    arrStrProducts(i) = objProduct.Name
    i = i + 1
Next

WScript.Echo Join(arrStrProducts, vbNewLine)

Now, if that works, then try the same thing with wbemtest.

  1. Launch the wbemtest program.
  2. Click Connect...
  3. Change rootdefault to rootcimv2, then click Connect.
  4. Click Query...
  5. Enter Select * from Win32_Product, then click Apply.

This should return a list of products. If it does, then WMI is probably fine, and something is up with WMIC. If the script worked, but this did not, try the following at a Command Prompt:

regsvr32 wbemdisp.dll

then run the wbemtest query again.

If neither the script nor the wbemtest work, then probably WMI is super hosed, and you’ll have to repair it.

Try

This is not a full list (wmic). This is only products installed with Windows Installer. There is no feature for everything.

However as I said in my previous post nearly everything is listed in the registry.

So to see it in a command prompt

reg query HKLMSOFTWAREMicrosoftWindowsCurrentVersionUninstall /s

Also your error code seems invalid. There is no 27a windows error or 0xc000027a NT Status code. It seems wrong for a COM containing NTSTatus 0xd000027a or COM with Windows error 0x8007027a.

Clean Booting

Each of the three steps turns of programs, services, and drivers in increasing amounts. Thus narrowing down the possible culprits.

Clean Boot

Click Start — All Programs — Accessories — Run and type

msconfig

Then go to the Startup tab. Untick everything. Then go to the Services tab. Tick Hide All Microsoft Services and untick everything that’s left.

Reboot. If this solves your problem reenable ½ of the services/startup items until you find which one.

Advanced Clean Boot

If the above doesn’t help.

Download Autoruns from http://technet.microsoft.com/en-us/sysinternals/bb963902.aspx

Start the program by right clicking and choosing Run As Administrator and click Options menu — Filter Options and tick Hide Microsoft entries and clear Include Empty Locations. Untick everything left.

Reboot. If this solves your problem reenable ½ of the items until you find which one.

Safe Mode

If the above doesn’t help.

Use Safe Mode with Networking if you need internet access.

Click Start — All Programs — Accessories — Run and type

msconfig

Then go to the Boot tab and click Safe Boot (also tick Network if needed). Reboot. Come back here and untick Safe Boot to return to normal mode.

or

If your computer has a single operating system installed, repeatedly press the F8 key as your computer restarts. You need to press F8 before the Windows logo appears. If the Windows logo appears, you will need to try again. [From Start — Help and Support]

Startup Repair

If your computer has a single operating system installed, repeatedly press the F8 key as your computer restarts. You need to press F8 before the Windows logo appears. If the Windows logo appears, you will need to try again. [From Start — Help and Support].

On the Advanced Boot Options screen, use the arrow keys to highlight Repair your computer, and then press ENTER.

Select Startup Repair.

Startup repair makes a log file. See C:WindowsSystem32LogFilesSrtSrtTrail.txt.

To access if Windows won’t start, on the Advanced Boot Options screen, use the arrow keys to highlight Repair your computer, and then press ENTER.

Select Command Prompt.

Type

type C:WindowsSystem32LogFilesSrtSrtTrail.txt |more

Also type explorer in your command prompt and see what happens.

My Explorer fixes listsways of using windows without the graphical shell.

To See if a Fix is Available

In Control Panel (and select Classic view in the left hand pane) choose Problem Reports and Solutions (type problem in Start’s search box), go to Problem History, right click your error and choose Check For Solution.

You may also right click and choose Details for more info. Post those details here. The Fault Module Name is the important information.

If the problem affects Control Panel press Winkey + R and type wercon (or type it in a command prompt).


Close Explorer and Start a Command Prompt

Close any Explorer windows

Start — All Programs — Accessories — Right click Command Prompt and choose Run As Administrator.

Click Start. Ctrl + Shift + Right click a blank spot (just above the power buttons is one place) then Exit Explorer.

Press Ctrl + Alt + Delete then Task Manager.

Check all explorer processes are closed. On the Process tab select explorer and right click and choose End Process, repeat if more than one explorer in the list.

Then to restart explorer after trying each of the following

Press Ctrl + Alt + Delete and choose Task Manager

In Task Manager click the File menu then New Task (Run) and type explorer


If You Can’t Start Explorer at All

Press Ctrl + Alt + Delete and choose Task Manager

On the Process tab click Show Processes From All Users to elevate to Administrator
In Task Manager click the File menu then New Task (Run) and type cmd
Other things you can try typing

Explorer
Explorer c:
Explorer /e,c:
wercon
control
iexplore
rstrui

If you can’t start a folder window use the Browse button in the New Task dialog. Remember you need to right click and choose Open rather than double clicking.


  • Remove From My Forums
  • Вопрос

  • Windows 2003 Server Standard Edition SP2. Только что переустановил, никакого другого софта еще не установлено. При запуске из консоли wmic product get name выдается ошибка:

    Узел — имя_компьютера

    ОШИБКА:

    Код = 0x80041010

    Описание = Недопустимый класс

    Услуга WMI

    Службы WMI запущены и функционируют нормально. На другие параметры wmic откликается а вот на wmic product не хочет. Может кто нибудь знает как это лечится? при поиске данной ошибки заметил, что у многих не работает в указанной ОС.

Ответы

  • а погуглить не судьба?

    доустановите компоненту WMI Windows Installer Provider (AddRemove Programs -> AddRemove Windows components -> Management and Monitoring tools)

    ——————————

    проверил — работает

    C:Documents and SettingsAdministrator>wmic product
    Node — DHCPSRV
    ERROR:
    Code = 0x80041010
    Description = Invalid class
    Facility = WMI

    C:Documents and SettingsAdministrator>wmic product
    Caption                                      Description
    VMware Tools                                 VMware Tools
    Microsoft .NET Framework 2.0 Service Pack 1  Microsoft .NET Fram
    Microsoft File Server Migration Toolkit      Microsoft File Serv
    Windows Support Tools                        Windows Support Too

    • Помечено в качестве ответа

      15 сентября 2010 г. 9:14

Я пытаюсь получить статистику PCoIP, доступную через WMI, я использую следующую команду для WMIC

 wmic path Win32_PerfRawData_TeradiciPerf_PCoIPSessionNetworkStatistics

или с powershell

powershell Get-WmiObject -namespace "rootcimv2" -computername computer01 -class Win32_PerfRawData_TeradiciPerf_PCoIPSessionNetworkStatistics

Однако, когда я попытался запустить любую команду, разветвленную через другой процесс, в этом случае это был python, и, передавая stdout, я получаю недопустимую ошибку класса, как показано ниже.

 Get-WmiObject : Invalid class
At line:1 char:14
+ Get-WmiObject <<<  -namespace rootcimv2 -computername computer01 -class
Win32_PerfRawData_TeradiciPerf_PCoIPSessionNetworkStatistics
+ CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

если это помогает, вывод команды powershell через командную строку

__GENUS                   : 2
__CLASS                   : Win32_PerfRawData_TeradiciPerf_PCoIPSessionNetworkS
tatistics
__SUPERCLASS              : Win32_PerfRawData
__DYNASTY                 : CIM_StatisticalInformation
__RELPATH                 : Win32_PerfRawData_TeradiciPerf_PCoIPSessionNetworkS
tatistics.Name="PCoIP Session"
__PROPERTY_COUNT          : 19
__DERIVATION              : {Win32_PerfRawData, Win32_Perf, CIM_StatisticalInfo
rmation}
__SERVER                  : DEMO-VSGA-WS01
__NAMESPACE               : rootcimv2
__PATH                    : DEMO-VSGA-WS01rootcimv2:Win32_PerfRawData_Terad
iciPerf_PCoIPSessionNetworkStatistics.Name="PCoIP S
ession"
Caption                   :
Description               :
Frequency_Object          : 0
Frequency_PerfTime        : 10000000
Frequency_Sys100NS        : 10000000
Name                      : PCoIP Session
RoundTripLatencyms        : 284
RXBWkbitPersec            : 22034
RXBWPeakkbitPersec        : 4
RXPacketLossPercent       : 112
RXPacketLossPercent_Base  : 28805
Timestamp_Object          : 0
Timestamp_PerfTime        : 299873128867
Timestamp_Sys100NS        : 130641888164850000
TXBWActiveLimitkbitPersec : 1832
TXBWkbitPersec            : 75615
TXBWLimitkbitPersec       : 90000
TXPacketLossPercent       : 7
TXPacketLossPercent_Base  : 30942

Я также пытался использовать python-модуль WMI

hostname = os.getenv('COMPUTERNAME', '')
c = wmi.WMI (hostname, namespace="rootcimv2")
print c.Win32_PerfRawData_TeradiciPerf_PCoIPSessionNetworkStatistics

Я получаю следующую ошибку

print c.Win32_PerfRawData_TeradiciPerf_PCoIPSessionNetworkStatistics
File "c:usersramesh~1appdatalocaltempeasy_install-tlfipcWMI-1.4.9-py2.7
-win32.egg.tmpwmi.py", line 1147, in __getattr__
File "C:Python27libsite-packageswin32comclientdynamic.py", line 522, in
__getattr__
raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: winmgmts://computer01/root/cimv2.Win32_PerfRawData_TeradiciP
erf_PCoIPSessionNetworkStatistics

Может ли это быть связано с уровнем олицетворения и аутентификации вызывающего?

ОБНОВИТЬ

Я переместил команду powershell в файл bat, когда я запускаю bat файл через CMD, он снова работает нормально.

Когда Popen через python, он показывает ту же ошибку. Если это помогает, я использую код python.

p = subprocess.Popen ('bat.bat',stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print p.stdout.read()

Я попробовал перечислить классы под пространством имен, класс был указан, когда файл bat был вызван через CMD, когда Popen, ни один из классов Teradici не был доступен. Командная строка в bat.bat

powershell Get-WmiObject -namespace "rootcimv2" -computername computer01 -list

Все это выполняется на VMWare VDI (Virtual Desktop Infrastructure), могут ли быть какие-либо ограничения политики?

После устранения неполадок в какой-то момент, по-видимому, причина в том, что требуемый класс не был доступен из 32-битных программ, хотя, когда я пробовал через PowerShell (x64 и x86), я получил правильные ответы.

В противном случае доступ к 64-битовому провайдеру WMI можно получить через 32-битную программу или наоборот, правильно настроив флаги Контекст WMI __ProviderArchitecture & __RequiredArchitecture WMI,

пифонический пример выглядит следующим образом

import win32com.client
import wmi
import os

objCtx = win32com.client.Dispatch("WbemScripting.SWbemNamedValueSet")
if self.is64Windows():
    objCtx.Add ("__ProviderArchitecture",  64)
else:
    objCtx.Add ("__ProviderArchitecture",  32)
objCtx.Add ("__RequiredArchitecture", True)
server = wmi.connect_server (server = "localhost", namespace="rootcimv2", named_value_set=objCtx)
connection = wmi.WMI (wmi = server)

Более подробную информацию о Context Flags можно найти в msdn

  • http://msdn.microsoft.com/en-us/library/aa393067%28v=vs.85%29.aspx
  • http://msdn.microsoft.com/en-us/library/aa390789%28v=vs.85%29.aspx

Кроме того, для отладки и устранения неполадок WMI вы можете обратиться к

  • http://msdn.microsoft.com/en-us/library/aa394603%28v=vs.85%29.aspx
  • http://msdn.microsoft.com/en-us/library/aa392285%28v=vs.85%29.aspx

Любой бывалый Windows-админ периодически сталкивается с проблемами в работе службы WMI (Windows Management Instrumentation) и ее компонентах. Наличие проблем в подсистеме WMI является критичным с точки зрения нормального функционирования Windows, поэтому администратору необходимо проверить и восстановить работоспособность WMI. В этой статье мы опишем простую методику диагностирования и устранения неполадок службы WMI в Windows.

О наличии проблем с WMI может свидетельствовать широкий спектр ошибок:

  • Ошибки обработки WMI запросов в системных журналах и логах приложений (
    0x80041002 - WBEM_E_NOT_FOUND
    ,
    WMI: Not Found
    ,
    0x80041010 WBEM_E_INVALID_CLASS
    );
  • Ошибки обработки GPO, связанные на WMI ( некорректная работа wmi фильтров групповых политик, и пр.);
  • WMI запросы выполняются очень медленно;
  • Ошибки при установке или работе агентов SCCM/SCOM;
  • Ошибки в работе скриптов (vbs или PowerShell), использующих пространство имен WMI (скрипты с Get-WmiObject и т.д.).

Содержание:

  • Диагностика проблем с WMI
  • Исправление WMI репозитория, перерегистрация библиотек, перекомпиляция MOF файлов
  • Сброс и пересоздание WMI репозитория (хранилища)

Диагностика проблем с WMI

В первую очередь нужно проверить служба Windows Management Instrumentation (Winmgmt) установлена в Windows и запущена. Вы можете проверить состояние службы в консоли services.msc или с помощью PowerShell:

Get-Service Winmgmt | Select DisplayName,Status,ServiceName

служба Windows Management Instrumentation (Winmgmt) работает

Если служба Winmgmt запущена, вы можете проверить работоспособность WMI, обратившись к ней с помощью простого WMI-запроса. Вы можете выполнить wmi запрос из командной строки или из PowerShell. Например, следующая команда выведет список установленных в Windows программ:

wmic product get name,version

Простейшая PowerShell команда для получения информации о версии и билда Windows 10 через WMI может выглядеть так:

get-wmiobject Win32_OperatingSystem

powershell проверка работы wmi командой get-wmiobject

Как вы видите, служба WMI ответила на запрос корректно. Если при выполнении такого WMI-запроса Windows возвращает ошибку, скорее всего сервиса WMI работает некорректно, поврежден WMI репозиторий или есть какие-то другие проблемы.

ошибка Failed to initialize all required WMI classes

В моем случае, например, при открытии свойств WMI Control в консоли управления компьютером (compmgmt.msc) появлялась надпись:

Failed to initialize all required WMI classes
Win32_Processor. WMI: Invalid namespace
Win32_WMISetting. WMI: Invalid namespace
Win32_OperationSystem. WMI: Invalid namespace

Ранее для диагностики WMI существовала официальная утилита от Microsoft – WMIDiag.vbs (Microsoft WMI Diagnosis). WMIdiag это vbs скрипт, который проверяет различные подсистемы WMI и записывает собранную информацию в лог файлы (по умолчанию логи находятся в каталоге %TEMP% — C:USERS%USERNAME%APPDATALOCALTEMP). Получившийся отчет состоит из файлов, имена которых начинаются с WMIDIAG-V2.2 и включает в себя следующие типы фалов:

  • .log файлы содержат подробный отчет об активности и работе утилиты WMIDiag;
  • .txt файлы содержат итоговые отчеты о найденных ошибках, на которые стоит обратить внимание;
  • В .csv файлах содержится информация, нужная для долгосрочного анализа работы подсистемы WMI.

скрипт для исправления ошибок WMI WMIDiag.vbs

Совет. В 64 битных версиях Windows wmidiag нужно запускать так:

c:windowsSystem32cscript.exe wmidiag.vbs

в противном случае появится ошибка:

WMIDiag must be run from native 64-bit environment. It is not supported in Wow64.

WMIDiag It is not supported in Wow64

После окончания работы утилиты WMIDiag администратор должен изучить полученные файлы логов, проанализировать и попытаться исправить найденные ошибки.

К сожалению, последняя версия WMIDiag 2.2 корректно работает только с версиями до Windows 8.1/Windows Server 2012 R2. На данный момент Microsoft даже удалила ссылку на загрузку WMIDiag из Download Center. Но при желании, этот скрипт можно найти в сети.

WMIDiag может дать подробную информацию по исправлению частных ошибок в WMI, но в большинстве случаев процесс это довольно трудоемкий и стоит потраченного времени только при решении инцидентов в критичных системах (как правило, на продуктивных серверах). Для массового сегмента рабочих станций пользователей сбросить и пересоздатьWMI репозиторий в Windows.

Исправление WMI репозитория, перерегистрация библиотек, перекомпиляция MOF файлов

В Windows 10/Windows Server 2016 вы можете проверить целостность репозитория WMI с помощью команды:

winmgmt /verifyrepository

winmgmt-verifyrepository - проверка состояния репозитория wmi

Если команда возвращает, что база данных WMI находится в неконсистентном состоянии (INCONSISTENT или WMI repository verification failed), стоит попробовать выполнить “мягкое” исправление ошибок репозитория:

Winmgmt /salvagerepository

WMI repository has been salvaged.

Данная команда выполняет проверку согласованности хранилища WMI и при обнаружении несогласованности перестраивает базу данных WMI.

Перезапустите службу WMI:

net stop Winmgmt
net start Winmgmt

Если стандартный способ исправления ошибок в WMI не помог, попробуйте следующий скрипт. Данный скрипт представляет собой ”мягкий” вариант восстановления службы WMI на компьютере (выполняется перерегистрация dll библиотек и службы WMI, перекомпилируются mof файлы). Данная процедура является безопасной и ее выполнение не должно привести к каким-либо новым проблемам с системой.

sc config winmgmt start= disabled
net stop winmgmt
cd %windir%system32wbem
for /f %s in ('dir /b *.dll') do regsvr32 /s %s
wmiprvse /regserver
sc config winmgmt start= auto
net start winmgmt
for /f %s in ('dir /b *.mof') do mofcomp %s
for /f %s in ('dir /b *.mfl') do mofcomp %s

На 64 битной версии Windows эти действия нужно также выполнить для каталога SysWOW64. Замените третью строку на

cd %windir%SysWOW64wbem

bat скрипт для перерегистрации компонентов wmi

Указанные команды можно выполнить путем простой вставки в окно командой строки, либо сохранить код в bat файле wmi_soft_repair.bat и запустить его с правами администратора. После окончания работы скрипта, перезагрузите Windows и проверьте работу WMI.

Сброс и пересоздание WMI репозитория (хранилища)

Если вам не помогли мягкие способ восстановления WMI, рассмотренные выше, придется перейти к более “жесткому” способу восстановления работоспособности службы WMI, заключающегося в пересоздании хранилищаWMI.

WMI репозиторий (хранилище) находится в каталоге
%windir%System32WbemRepository
и представляет собой базу данных, в которой содержится информация о метаданных и определениях WMI классов. В некоторых случаях WMI репозиторий может содержать статическую информацию классов. При повреждении репозитория WMI, в работе службы Windows Management Instrumentation (Winmgmt) могут наблюдаться ошибки вплоть до полной невозможности ее запустить.

Если вы подозреваете, что репозиторий WMI поврежден, имейте в виду, что его пересоздание — это последняя шаг, к которому нужно прибегнуть только тогда, когда другие операции не помогают реанимировать WMI.

Следующая команда выполнит сброс базы данных WMI к исходному состоянию (как после чистой установки Windows). Используйте эту команду для выполнения hard reset репозитория WMI, если параметре salvagerepository не исправил проблему:

Winmgmt /resetrepository

Совет. На практике бывают случаи, когда пересоздание хранилища WMI приводит к проблемам со сторонним софтом. Это связано с тем, что все записи в базе WMI обнуляются (до состояния чистой системы). Такие программы скорее всего, придется переустанавливать в режиме восстановления.

Если обе команды (
Winmgmt /salvagerepository
и
Winmgmt /resetrepository
) не восстановили консистентное состояние базы WMI, попробуйте выполнить “жесткое” пересоздание базы WMI вручную таким скриптом:

sc config winmgmt start= disabled
net stop winmgmt
cd %windir%system32wbem
winmgmt /resetrepository
winmgmt /resyncperf
if exist Repos_bakup rd Repos_bakup /s /q
rename Repository Repos_bakup
regsvr32 /s %systemroot%system32scecli.dll
regsvr32 /s %systemroot%system32userenv.dll
for /f %s in ('dir /b *.dll') do regsvr32 /s %s
for /f %s in ('dir /b *.mof') do mofcomp %s
for /f %s in ('dir /b *.mfl') do mofcomp %s
sc config winmgmt start= auto
net start winmgmt
wmiprvse /regserver

сброс и восстановление хранилища wmi в windows 10

На 64 битной версии Windows нужно также перерегистрировать dll/exe и перекомпилировать mof файлы в каталоге %windir%sysWOW64wbem.

Данный скрипт полностью пересоздает хранилище WMI (старый репозиторий сохраняется в каталог Repos_bakup). После окончания работы скрипта нужно перезагрузить Windows. Затем протестируйте работу службы WMI простым запросом.

Проверьте состояние WMI репозитория. Если ошибки исправлены, команда
winmgmt /verifyrepository
должна вернуть:

WMI repository is consistent

WMI repository is consistent

В этой статье мы собрали основные способы, позволяющие продиагностировать и устранить неполадки службы и репозитория WMI.

  • Remove From My Forums
  • Question

  • Hello there,

    I’m an IT technician in company and I have encountered and issue with one of our employees Windows 10 PC.

    He need to you for his programming the command ‘getmac’ and its not working and getting the «error: invalid class».

    I tried to run SFC /scannow and dism /restore and it fixed some errors but still it didn’t solve this issue.

    Please assist.

    Thanks,

    Aviad

    • Moved by

      Tuesday, November 15, 2016 1:35 PM
      Move to more appropriate forum

    • Changed type
      MeipoXuMicrosoft contingent staff
      Wednesday, November 16, 2016 6:30 AM
  • Remove From My Forums
  • Question

  • Hello there,

    I’m an IT technician in company and I have encountered and issue with one of our employees Windows 10 PC.

    He need to you for his programming the command ‘getmac’ and its not working and getting the «error: invalid class».

    I tried to run SFC /scannow and dism /restore and it fixed some errors but still it didn’t solve this issue.

    Please assist.

    Thanks,

    Aviad

    • Moved by

      Tuesday, November 15, 2016 1:35 PM
      Move to more appropriate forum

    • Changed type
      MeipoXuMicrosoft contingent staff
      Wednesday, November 16, 2016 6:30 AM

You can receive error 0x80041010 from multiple applications that call WMI. For my example it was received in SCCM while patches were being applied.

WMI - Configuration Manager Trace Log Error

No matter where you got the error the underlying issue is probably with WMI. Here is how to check!

Confirm WMI is Broken:

Launch the WMI MMC snapin by Start -> Run -> then enter WMIMGMT.MSC

Right click WMI Control (Local) and click Properties

WMI 1 - wmimgmt.msc

If WMI is working properly then it will show that Good Properties. If you see Invalid class then your WMI is not working correctly.

Bad

Good

Troubleshooting:

The first step is to download the Microsoft WMIDiag Tool. It will analyze WMI and give you a report with any issues it finds.

When you run the downloaded .EXE it will ask you where to extract the files. Once extracted right click the WMIDiag VBScript and click Open with Command Prompt

WMI 3 - WMIDiag Tool

Here is what the script looks like while it runs:

WMIDiag - Script Running

Once complete you will get a text file of the results. Here you should be able to narrow down the cause of your WMI issue. In my case there are issues with .MOF registrations.

WMI 4 - WMIDiag Results

Resolve MOF Registration Errors:

To resolve MOF Registration errors the following commands need to be ran from an elevated command prompt. It will reregister all .MOF files with WMI.

CD C:WindowsSystem32WBEM dir /b *.mof *.mfl | findstr /v /i uninstall > moflist.txt & for /F %s in (moflist.txt) do mofcomp %s

Here is what the command looks like while it runs:

WMI 5 - MOF Registration

Once finished check WMIMGMT.MSC to see if it is populating the Properties correctly.

Good

How can I troubleshoot and fix Get-Net* PowerShell cmdlets? All of the following are failing with Invalid class. I’m using Windows 10, version 1511 and do not have the option to upgrade to 1607 at this point.

First PowerShell version:

PS C:WINDOWSsystem32> $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
5      0      10586  672

Errors:

PS C:WINDOWSsystem32> Get-NetAdapter
Get-NetAdapter : Invalid class
At line:1 char:1
+ Get-NetAdapter
+ ~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (MSFT_NetAdapter:ROOT/StandardCimv2/MSFT_NetAdapter) [Get-NetAdapter], CimException
    + FullyQualifiedErrorId : HRESULT 0x80041010,Get-NetAdapter

PS C:WINDOWSsystem32> Get-NetIPAddress
Get-NetIPAddress : Invalid class
At line:1 char:1
+ Get-NetIPAddress
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (MSFT_NetIPAddress:ROOT/StandardCimv2/MSFT_NetIPAddress) [Get-NetIPAddress], CimException
    + FullyQualifiedErrorId : HRESULT 0x80041010,Get-NetIPAddress

PS C:WINDOWSsystem32> Get-NetAdapterHardwareInfo
Get-NetAdapterHardwareInfo : Invalid class
At line:1 char:1
+ Get-NetAdapterHardwareInfo
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (MSFT_NetAdapterHardwareInfoSettingData:ROOT/StandardCi...InfoSettingData
   ) [Get-NetAdapterHardwareInfo], CimException
    + FullyQualifiedErrorId : HRESULT 0x80041010,Get-NetAdapterHardwareInfo

PS C:WINDOWSsystem32> Get-NetAdapterBinding
Get-NetAdapterBinding : Invalid class
At line:1 char:1
+ Get-NetAdapterBinding
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (MSFT_NetAdapterBindingSettingData:ROOT/StandardCi...dingSettingData) [Ge
   t-NetAdapterBinding], CimException
    + FullyQualifiedErrorId : HRESULT 0x80041010,Get-NetAdapterBinding

PS C:WINDOWSsystem32> Get-NetAdapterStatistics -Name "Wi-Fi"
Get-NetAdapterStatistics : Invalid class
At line:1 char:1
+ Get-NetAdapterStatistics -Name "Wi-Fi"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (MSFT_NetAdapterStatisticsSettingData:ROOT/StandardCi...ticsSettingData)
   [Get-NetAdapterStatistics], CimException
    + FullyQualifiedErrorId : HRESULT 0x80041010,Get-NetAdapterStatistics

PS C:WINDOWSsystem32> Get-NetAdapterStatistics -Name "Ethernet"
Get-NetAdapterStatistics : Invalid class
At line:1 char:1
+ Get-NetAdapterStatistics -Name "Ethernet"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (MSFT_NetAdapterStatisticsSettingData:ROOT/StandardCi...ticsSettingData)
   [Get-NetAdapterStatistics], CimException
    + FullyQualifiedErrorId : HRESULT 0x80041010,Get-NetAdapterStatistics

I’m trying to use Docker for Windows 10 (which used to work) but the PowerShell failures are causing Docker to not start (GitHub issue). The errors are occurring on my host, not inside Docker containers. For the sake of this question you should ignore the Docker details, it is just that I cannot use Docker due to this problem.

I get a Internal server error when I try to get product name with the following code :

// I get product ID from the database in the $product_id variable

$product_factory = new WC_Product_Factory();
$product         = $product_factory ->get_product($product_id);

I get this error :

«PHP Fatal error: Uncaught Error: Call to a member function
get_name() on boolean in …»

Iłya Bursov's user avatar

Iłya Bursov

23.2k4 gold badges33 silver badges57 bronze badges

asked Aug 29, 2018 at 19:11

RG Blanco's user avatar

1

just add if statement before calling get_name() function as probably at some point your query is not returning the product id and that’s mean you product is null and you can’t call get_name() on null that’s why you are getting this error.

so your code should be like this:

$product_factory = new WC_Product_Factory();
$product = $product_factory->get_product($product_id);
if ($product) {
    echo $product->get_name();
}

answered Aug 29, 2018 at 19:46

kashalo's user avatar

kashalokashalo

3,4222 gold badges11 silver badges28 bronze badges

Понравилась статья? Поделить с друзьями:
  • Process hacker ошибка unable to start
  • Process finished with exit code 1073740791 0xc0000409 ошибка
  • Procedure too large vba ошибка как исправить
  • Probe open ошибка фанук
  • Pro tools ошибка при запуске