Powershell - Utiliser les requêtes WMI


Powershell - Utiliser les requêtes WMI


Voici comment on peut interroger à distance une information contenu dans les Windows Management Instrumentation (WMI) d'un poste.

$remoteuserlist = Get-WmiObject -query "SELECT * FROM Win32_UserAccount WHERE LocalAccount = 'True' and Name != 'Guest'" –computername $PC -verbose
Depuis la version 3 de PowerShell, il a été créé les commandes CIM, pour améliorer les temps de réponses et utilisation à distance des commandes WMI.

#requires -Version 3
Get-CimInstance -query 'SELECT * FROM Win32_logicaldisk where DriveType="3" and DriveType="2"'
Voici par exemple, une petite comparaison sur des requêtes simples :
Comparatif entre WMI et CIM
Commande WMITempsCommande CIMTemps
Get-WmiObject Win32_ComputerSystem20,6793 msGet-ciminstance Win32_ComputerSystem16,0279 ms
Get-WmiObject Win32_ComputerSystem -Property * | Select-Object * | Format-List *23,8446 msGet-ciminstance Win32_ComputerSystem -Property * | Select-Object * | Format-List *18,826 ms
La famille des commandes WMI se résume aux cinq commandes suivantes :

Correspondance entre les commandes WMI et CIM
CommandeletteDescriptionÉquivalent CIM
Get-WmiObject
Récupère les instances d’une classe.
Get-CimInstance
Invoke-WmiMethod
Invoque une instance ou une méthode statique d’une classe.
Invoke-CimMethod
Register-WmiEvent
S’abonne à un événement WMI/CIM.
Register-CimIndicationEvent
Remove-WmiObject
Supprime une ou plusieurs instances de classe.
Remove-CimInstance
Set-WmiInstance

Modifie une ou plusieurs instances d’une classe.

Set-CimInstance
Pour tester les requêtes, on peut utiliser l'application WMI Explorer disponible sur ce site

Pour les utilisateurs de l'outil PowerShell ISE, je vous recommande l'add-on, PowerShell ISE Addon - CIM Explorer

Exemple de requête:

J'ai eu l'occasion d'utiliser l'ensemble des requêtes qui suivent:
NomDescriptionEspace de nomsRequête
Client Windows 10Afficher la Version,le ProductType et l'architecture quand les postes sont sous Windows 10root\CIMv2select Version,ProductType,OSArchitecture from Win32_OperatingSystem where (Version like “10.%”) and ProductType = “1”
Client Windows 10 x86Afficher la Version,le ProductType et l'architecture quand les postes sont sous Windows 10 32 bitroot\CIMv2select Version,ProductType,OSArchitecture from Win32_OperatingSystem where (Version like “10.%”) and ProductType = “1” and OSArchitecture=“32 bits”
Client Windows 10 x64Afficher la Version,le ProductType et l'architecture quand les postes sont sous Windows 10 64 bitroot\CIMv2select Version,ProductType,OSArchitecture from Win32_OperatingSystem where (Version like “10.%”) and ProductType = “1” and OSArchitecture=“64 bits”
Windows 10 EnterpriseAfficher la Version,le ProductType et l'architecture quand les postes sont sous Windows 10 Entrepriseroot\CIMv2SELECT Version, ProductType, Caption FROM Win32_OperatingSystem WHERE Version LIKE '10.%' AND ProductType='1' AND Caption LIKE '%Ent%'
Windows Server 2012-root\CIMv2select * from Win32_OperatingSystem where Version like “6.2%” and ProductType = “3”
Windows 8-root\CIMv2select * from Win32_OperatingSystem where Version like “6.2%” and ProductType = “1”
Windows Server 2008 R2-root\CIMv2select * from Win32_OperatingSystem where Version like “6.1%” and ProductType = “3”
Windows 7-root\CIMv2select * from Win32_OperatingSystem where Version like “6.1%” and ProductType = “1”
Windows 7 EnterpriseWMI Filter : Only Windows 7 Enterprise Editionsroot\CIMv2SELECT Version, ProductType, Caption FROM Win32_OperatingSystem WHERE Version LIKE '6.1.%' AND ProductType='1' AND Caption LIKE '%Ent%'
Windows Server 2008-root\CIMv2select * from Win32_OperatingSystem where Version like “6.0%” and ProductType = “3”
Windows Vista-root\CIMv2select * from Win32_OperatingSystem where Version like “6.0%” and ProductType = “1”
Windows Server 2003-root\CIMv2select * from Win32_OperatingSystem where Version like “5.2%” and ProductType = “3”
Windows XP-root\CIMv2select * from Win32_OperatingSystem where (Version like “5.1%” or Version like “5.2%”) and ProductType = “1”
Résolution 16:9Sortir la résolution de l'écran d'un poste dans la résolution à un ratio 16:9root\CIMv2SELECT ScreenWidth, ScreenHeight FROM Win32_DesktopMonitor WHERE ScreenWidth='1280' AND ScreenHeight='800' OR ScreenWidth='1440' AND ScreenHeight='900' OR ScreenWidth='1680' AND ScreenHeight='1050' OR ScreenWidth='1920' AND ScreenHeight='1080' OR ScreenWidth='1280' AND ScreenHeight='768'
Résolution 4:3Sortir la résolution de l'écran d'un poste dans la résolution à un ratio 4:3root\CIMv2SELECT ScreenWidth, ScreenHeight FROM Win32_DesktopMonitor WHERE ScreenWidth='1024' AND ScreenHeight='768'
Résolution 5:4Sortir la résolution de l'écran d'un poste dans la résolution à un ratio 5:4root\CIMv2SELECT ScreenWidth, ScreenHeight FROM Win32_DesktopMonitor WHERE ScreenWidth='1280' AND ScreenHeight='1024'
ServeurSortir uniquement les serveursroot\CIMv2Select * from Win32_ComputerSystem where DomainRole <> 0 and DomainRole <>1
OS x86Filtre les systèmes d'exploitation en x86root\CIMv2SELECT AddressWidth FROM Win32_Processor WHERE AddressWidth='32'
OS x64Filtre les systèmes d'exploitation en x64root\CIMv2SELECT AddressWidth FROM Win32_Processor WHERE AddressWidth='64'
LaptopsFiltre les postes Laptops qui possèdent un statu de batterieroot\CIMv2Select * from Win32_Battery WHERE (BatteryStatus <> 0)
Dell Manufacturer is Dell:
SELECT * FROM Win32_ComputerSystem WHERE Manufacturer LIKE "%Dell%"
Models from Dell:
SELECT * FROM Win32_ComputerSystem WHERE Model LIKE "%Latitude E7440%"
SELECT * FROM Win32_ComputerSystem WHERE Model LIKE "%Optiplex 990%"
SELECT * FROM Win32_ComputerSystem WHERE Model LIKE "%Precision M6800%"
SELECT * FROM Win32_ComputerSystem WHERE Model LIKE "%Venue 11 Pro 7130%"
Hewlett-Packard Manufacturer is Hewlett-Packard:
SELECT * FROM Win32_ComputerSystem WHERE Manufacturer LIKE "%Hewlett-Packard%"
Models from Hewlett-Packard:
SELECT * FROM Win32_ComputerSystem WHERE Model LIKE "%HP EliteBook 8540p%“
SELECT * FROM Win32_ComputerSystem WHERE Model LIKE "%HP EliteBook 8560w%"
SELECT * FROM Win32_ComputerSystem WHERE Model LIKE "%ElitePad 1000%"
Lenovo Manufacturer is Lenovo:
SELECT * FROM Win32_ComputerSystem WHERE Manufacturer LIKE "%Lenovo%"
Models from Lenovo:
SELECT * FROM Win32_ComputerSystemProduct WHERE Version LIKE "%ThinkPad T420%"
SELECT * FROM Win32_ComputerSystemProduct WHERE Version LIKE "%ThinkPad W520%"
SELECT * FROM Win32_ComputerSystemProduct WHERE Version LIKE "%ThinkPad Edge E330%"
SELECT * FROM Win32_ComputerSystemProduct WHERE Version LIKE "%ThinkPad Tablet 2%"
Microsoft Hyper-V
SELECT * FROM Win32_ComputerSystem WHERE Manufacturer LIKE "%Microsoft Corporation%" AND Model LIKE "%Virtual Machine%"
VMWare
SELECT * FROM Win32_ComputerSystem WHERE Manufacturer LIKE "%VMware%" AND Model LIKE "%VMware Virtual Platform%"

Utiliser WMI pour générer une table contenant l'ensemble des informations des disques durs

Pour l'un de mes derniers projets, j'ai eu besoin de récupérer le numéro du disque dur qui correspondait à la lettre que l'on devait sélectionner dans ce programme, c'est pour cela que j'ai fait deux modules.

Function ConvertLetterToDisk(){
    Param ( $letter )
    $hash = Get-CimInstance -ClassName Win32_DiskDrive | ForEach-Object {
  $diskWmi = $_
  $PartsWmi = "ASSOCIATORS OF " +
                "{Win32_DiskDrive.DeviceID='$($diskWmi.DeviceID)'} " +
                "WHERE AssocClass = Win32_DiskDriveToDiskPartition"
  Get-CimInstance -Query $PartsWmi | ForEach-Object {
    $PartWmi = $_
    $drives = "ASSOCIATORS OF " +
              "{Win32_DiskPartition.DeviceID='$($PartWmi.DeviceID)'} " +
              "WHERE AssocClass = Win32_LogicalDiskToPartition"
    Get-CimInstance -Query $drives | ForEach-Object {
      New-Object -Type PSObject -Property @{
        DiskNumber  = $diskWmi.DeviceID.Replace('\\.\PHYSICALDRIVE','')
        DiskSize    = $diskWmi.Size
        DiskModel   = $diskWmi.Model
        Partition   = $PartWmi.Name
        RawSize     = $PartWmi.Size
        DriveLetter = $_.DeviceID
        VolumeName  = $_.VolumeName
        Size        = $_.Size
        FreeSpace   = $_.FreeSpace
      }
    }
  }
}
$hash | Where-Object Driveletter -Match $letter | ForEach-Object {
Set-Variable -Name Value -Value $_.DiskNumber
}
    return $Value
}


Function ConvertDiskToLetter(){
    Param ( $Disk )
$hash = Get-CimInstance -ClassName Win32_DiskDrive | ForEach-Object {
  $diskWmi = $_
  $PartsWmi = "ASSOCIATORS OF " +
                "{Win32_DiskDrive.DeviceID='$($diskWmi.DeviceID)'} " +
                "WHERE AssocClass = Win32_DiskDriveToDiskPartition"
  Get-CimInstance -Query $PartsWmi | ForEach-Object {
    $PartWmi = $_
    $drives = "ASSOCIATORS OF " +
              "{Win32_DiskPartition.DeviceID='$($PartWmi.DeviceID)'} " +
              "WHERE AssocClass = Win32_LogicalDiskToPartition"
    Get-CimInstance -Query $drives | ForEach-Object {
      New-Object -Type PSObject -Property @{
        DiskNumber  = $diskWmi.DeviceID.Replace('\\.\PHYSICALDRIVE','')
        DiskSize    = $diskWmi.Size
        DiskModel   = $diskWmi.Model
        Partition   = $PartWmi.Name
        RawSize     = $PartWmi.Size
        DriveLetter = $_.DeviceID
        VolumeName  = $_.VolumeName
        Size        = $_.Size
        FreeSpace   = $_.FreeSpace
      }
    }
  }
}
$hash | Where-Object DiskNumber -Match $Letter | ForEach-Object {
Set-Variable -Name Value -Value $_.DriveLetter
}
    return $Value
}

Commentaires

Posts les plus consultés de ce blog

Powershell - Supprimer Teams sur l'ensemble des profils utilisateurs

Powershell - Comment tester les ports TCP ?

MRemoteNG - Voir les mots de passe dans l'application