Tâches WMI : Mise en réseau

Les tâches WMI pour la gestion réseau et l’obtention d’informations sur les connexions et les adresses IP ou MAC. Pour obtenir d’autres exemples, consultez TechNet ScriptCenter à https://www.microsoft.com/technet.

Les exemples de script présentés dans cette rubrique obtiennent les données uniquement à partir de l’ordinateur local. Pour plus d’informations sur l’utilisation du script afin d’obtenir des données provenant d’ordinateurs distants, consultez Connexion à WMI sur un ordinateur distant.

La procédure suivante explique comment exécuter un script.

Pour exécuter un script

  1. Copiez le code, puis enregistrez-le dans un fichier avec l’extension .vbs, par exemple nomfichier.vbs. Vérifiez que votre éditeur de texte n’ajoute pas d’extension .txt au fichier.
  2. Ouvrez une fenêtre d’invite de commandes, puis accédez au répertoire où vous avez enregistré le fichier.
  3. Tapez cscript nomfichier.vbs à l’invite de commandes.
  4. Si vous ne pouvez pas accéder à un journal des événements, vérifiez si vous exécutez la commande à partir d’une invite de commandes avec élévation de privilèges. Certains journaux des événements, par exemple le journal des événements de sécurité, peuvent être protégés par la fonctionnalité UAC (contrôle de compte d’utilisateur).

Notes

Par défaut, cscript affiche la sortie d’un script dans la fenêtre d’invite de commandes. Dans la mesure où les scripts WMI peuvent produire de grandes quantités de données en sortie, vous pouvez être amené à rediriger la sortie vers un fichier. Tapez cscript nomfichier.vbs > fichiersortie.txtà l’invite de commandes pour rediriger la sortie du scriptnomfichier.vbs vers fichiersortie.txt.

Le tableau suivant liste des exemples de script qui peuvent être utilisés pour obtenir divers types de données à partir de l’ordinateur local.

Comment puis-je... Classes ou méthodes WMI
... désactiver une connexion réseau à l’aide de WMI ? Si vous utilisez DHCP, utilisez le Win32_NetworkAdapterConfiguration et la méthode ReleaseDHCPLease pour libérer l’adresse IP. Si vous n’utilisez pas DHCP, vous ne pouvez pas utiliser WMI pour désactiver une connexion réseau. Pour réactiver la connexion réseau, utilisez objNetCard.RenewDHCPLease. Vous pouvez également libérer ou renouveler tous les baux DHCP à l’aide des méthodes ReleaseDHCPLeaseAll et RenewDHCPLeaseAll.
VB
strComputer = "."
Set objWMIService = GetObject( _
    "winmgmts:\\" & strComputer & "\root\cimv2")
Set colNetCards = objWMIService.ExecQuery _
    ("Select * From Win32_NetworkAdapterConfiguration " _
        & "Where IPEnabled = True")
For Each objNetCard in colNetCards
    objNetCard.ReleaseDHCPLease()
Next
PowerShell
$Computer = "."
$net = Get-WMIObject -class Win32_NetworkAdapterConfiguration -ComputerName $computer
$netenabled = $net | where {$_.IPenabled}
foreach ($NetCard in $netenabled) {
    "Releasing lease on: {0}" -f $netcard.caption
 $netcard.ReleaseDHCPLease()
}
... désactiver ou activer une carte réseau ?

Utilisez la classe Win32_NetworkAdapter et les méthodes Désactiver ou Activer.

... déterminer quelle adresse IP a été affectée à une connexion réseau donnée ?

Utilisez la classe Win32_NetworkAdapter et la propriété NetConnectionID pour déterminer l’adresse MAC de la connexion réseau. Ensuite, utilisez la classe Win32_NetworkAdapterConfiguration pour rechercher l’adresse IP associée à l’adresse MAC.

VB
strComputer = "." Set objWMIService = GetObject(_ "winmgmts:\\" & strComputer & "\root\cimv2") Set colItems = objWMIService.ExecQuery _ ("Sélectionner* From Win32_NetworkAdapter " _ & "Where NetConnectionID = " & _ "'Local Area Connection 2'") 

For Each objItem in colItems strMACAddress = objItem.MACAddress Next

Set colItems = objWMIService.ExecQuery _ (« Sélectionner* From Win32_NetworkAdapterConfiguration »)

For Each objItem in colItems If objItem.MACAddress = strMACAddress Then For Each strIPAddress in objItem.IPAddress Wscript.Echo "IP Address: " & strIPAddress Next End If Next

VB
strComputer = "."
Set objWMIService = GetObject( _
    "winmgmts:\\" & strComputer & "\root\cimv2")
Set colNics = objWMIService.ExecQuery _
    ("Select * From Win32_NetworkAdapter " _
        & "Where NetConnectionID = " & _
        "'Local Area Connection'")
 
For Each objNic in colNics
    Set colNicConfigs = objWMIService.ExecQuery _
      ("ASSOCIATORS OF " _
          & "{Win32_NetworkAdapter.DeviceID='" & _
      objNic.DeviceID & "'}" & _
      " WHERE AssocClass=Win32_NetworkAdapterSetting")
    For Each objNicConfig In colNicConfigs
        For Each strIPAddress in objNicConfig.IPAddress
            Wscript.Echo "IP Address: " &  strIPAddress
        Next
    Next
Next
... déterminer l’adresse MAC d’une carte réseau ?

Utilisez la classe Win32_NetworkAdapterConfiguration et case activée la valeur de la propriété MACAddress.

... déterminer l’adresse IP d’un ordinateur ?

Utilisez la classe Win32_NetworkAdapterConfiguration et case activée la valeur de la propriété IPAddress. Cette valeur est retournée sous forme de tableau. Utilisez donc une boucle For-Each pour obtenir la valeur.

VB
strComputer = "."
Set objWMIService = GetObject( _ 
    "winmgmts:\\" & strComputer & "\root\cimv2")
Set IPConfigSet = objWMIService.ExecQuery _
    ("Select IPAddress from Win32_NetworkAdapterConfiguration ")
 
For Each IPConfig in IPConfigSet
    If Not IsNull(IPConfig.IPAddress) Then 
        For i=LBound(IPConfig.IPAddress) _
            to UBound(IPConfig.IPAddress)
                WScript.Echo IPConfig.IPAddress(i)
        Next
    End If
Next
PowerShell
$Computer = "."
$IPconfigset = Get-WmiObject Win32_NetworkAdapterConfiguration
  
# Iterate and get IP address
$count = 0
foreach ($IPConfig in $IPConfigSet) {
   if ($Ipconfig.IPaddress) {
      foreach ($addr in $Ipconfig.Ipaddress) {
   "IP Address   : {0}" -f  $addr;
   $count++ 
   }
   }
}
if ($count -eq 0) {"No IP addresses found"}
else {"$Count IP addresses found on this system"}
... configurer un ordinateur pour commencer à obtenir son adresse IP via DHCP ?

Utilisez la classe Win32_NetworkAdapterConfiguration et la méthode EnableDHCP.

VB
strComputer = "."
Set objWMIService = GetObject(_
    "winmgmts:\\" & strComputer & "\root\cimv2")
Set colNetAdapters = objWMIService.ExecQuery _
    ("Select * from Win32_NetworkAdapterConfiguration " _
        & "where IPEnabled=TRUE")
 
For Each objNetAdapter In colNetAdapters
    errEnable = objNetAdapter.EnableDHCP()
Next
... Attribuer une adresse IP statique à un ordinateur ?

Utilisez la classe Win32_NetworkAdapterConfiguration et la méthode EnableStatic.

VB
strComputer = "."
Set objWMIService = GetObject( _
    "winmgmts:\\" & strComputer & "\root\cimv2")
Set colNetAdapters = objWMIService.ExecQuery _
    ("Select * from Win32_NetworkAdapterConfiguration " _
        & "where IPEnabled=TRUE")
strIPAddress = Array("192.168.1.141")
strSubnetMask = Array("255.255.255.0")
strGateway = Array("192.168.1.100")
strGatewayMetric = Array(1)
 
For Each objNetAdapter in colNetAdapters
    errEnable = objNetAdapter.EnableStatic( _
        strIPAddress, strSubnetMask)
    errGateways = objNetAdapter.SetGateways(_
        strGateway, strGatewaymetric)
Next
... obtenir des informations sur les cartes réseau sans également récupérer des informations sur des éléments tels que les connexions RAS et VPN ?

Utilisez la classeWin32_NetworkAdapterConfiguration. Dans votre requête WQL , utilisez cette clause : Where IPEnabled = True.

VB
strComputer = "."
Set objWMIService = GetObject( _
    "winmgmts:\\" & strComputer & "\root\cimv2")
Set IPConfigSet = objWMIService.ExecQuery _
    ("Select IPAddress from Win32_NetworkAdapterConfiguration" _
        & " where IPEnabled=TRUE")
 
For Each IPConfig in IPConfigSet
    If Not IsNull(IPConfig.IPAddress) Then 
        For i=LBound(IPConfig.IPAddress) _
        to UBound(IPConfig.IPAddress)
            WScript.Echo IPConfig.IPAddress(i)
        Next
    End If
Next
... effectuer un test ping sur un ordinateur sans utiliser Ping.exe ?

Utilisez la classe Win32_PingStatus .

Win32_PingStatus pouvez retourner des données pour les ordinateurs qui ont à la fois des adresses IPv4 et des adresses IPv6.

VB
strComputer = "." Set objWMIService = GetObject(_ "winmgmts:\\" & strComputer & "\root\cimv2") Set colPings = objWMIService.ExecQuery _ ("Sélectionner* From Win32_PingStatus where Address = '192.168.1.1'") 

For Each objStatus in colPings If IsNull(objStatus.StatusCode) _ or objStatus.StatusCode<>0 Then WScript.Echo "Computer did not respond." Else Wscript.Echo "Computer responded." End If Next

VB
strComputer = "client1"
Set objShell = CreateObject("WScript.Shell")
Set objScriptExec = objShell.Exec( _
    "ping -n 2 -w 1000 " & strComputer)
strPingResults = LCase(objScriptExec.StdOut.ReadAll)
If InStr(strPingResults, "reply from") Then
    If InStr(strPingResults, "destination net unreachable") Then
        WScript.Echo strComputer & "did not respond to ping."
    Else
        WScript.Echo strComputer & " responded to ping."
    End If 
Else
    WScript.Echo strComputer & " did not respond to ping."
End If
  

Tâches WMI pour les scripts et les applications

Exemples d’applications WMI C++

TechNet ScriptCenter