Probleme for each = null ?

Résolu
leSaleGauSS Messages postés 148 Date d'inscription samedi 4 novembre 2006 Statut Membre Dernière intervention 4 décembre 2008 - 15 déc. 2006 à 21:47
leSaleGauSS Messages postés 148 Date d'inscription samedi 4 novembre 2006 Statut Membre Dernière intervention 4 décembre 2008 - 18 déc. 2006 à 22:08
Salut à tous
j'ai une boucle for each du genre :
   for each objDrive in colDrives
      'creation networkDrive
   next
Probleme : si colDrives est null alors il ne passe pas par la boucle
Question : comment savoir que colDrives est null ? (j'ai essayé de faire if coldrives="", <>"", =null)
Merci pour toutes réponses !

Quand je suis là tout va mal  

22 réponses

cs_JMO Messages postés 1854 Date d'inscription jeudi 23 mai 2002 Statut Membre Dernière intervention 24 juin 2018 27
16 déc. 2006 à 11:04
 Bonjour à tous

Salut 899656 leSaleGauSS ,

Que vient faire "WshNetwork.MapNetworkDrive" dans ton code ???

1) si tu utilises wbem et wmi, c'est pour se retrouver à la racine d'un server distant;
ex:
On Error Resume Next
Const WbemAuthenticationLevelPktPrivacy = 6
strCredentials = InputBox _
    ("Please enter the user name, a blank space, and then the password:", _
        "Enter User Credentials","administrateur admin")
If strCredentials = "" Then
    Wscript.Quit
End If



arrCredentials = Split(strCredentials," ")
strUser = arrCredentials(0)
strPassword = arrCredentials(1)
strNamespace = "root\cimv2"



Set objNetwork = CreateObject("Wscript.Network")
strLocalComputer = objNetwork.ComputerName



strComputer = InputBox _
    ("Please enter the name of the computer you want to connect to:", _
        "Enter Computer Name")



If strComputer = "" Then
    Wscript.Quit
End If
WScript.Echo strComputer
Set objWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objWMIService = objwbemLocator.ConnectServer _
    (strComputer, strNamespace, strUser, strPassword)
objWMIService.Security_.authenticationLevel = WbemAuthenticationLevelPktPrivacy

' =====================================================================
' Insert your code here' Set colItems objWMIService.ExecQuery _
    ("Select * From Win32_OperatingSystem")
For Each objItem in ColItems
    Wscript.Echo strComputer & ": " & objItem.Caption
Next



2) si tu veux seulement mapper certains disks d' un server distant, ce ne sera pas la même synthaxe.
    a) tu dois repérer les DriveLetter de libre sur ton server local;
    b) tu dois connaitre, par avance, les Driveletter que tu souhaites mapper sur ton server distant.
ex:

Const resultat = "D:\client_ACYR3PRO_espace_disk.txt"    ' fichier .txt en output.
Const adressIP = [file://\\xxx.xxx.xxx.xx\ \\xxx.xxx.xxx.xx\]  ' adresse IP du server distantC
Const user = "nom de connexion"
Const pssw = "password de connexion"Const libelle "Serveur Client - ACYR3PRO - " <?xml:namespace prefix o ns = "urn:schemas-microsoft-com:office:office" /??>




'lettre représente une des lettres (de mon poste local) que j'autorise pour le mappage
Dim lettre : lettre = Array("G","H","I","J","K","L","M","N","P","O","Q","R","S","T","V","W","X")








 




Dim  fso, rapport, i



Set fso = CreateObject("Scripting.fileSystemObject")

Set rapport = fso.openTextFile(resultat, 2, True) 



 







' Par rapport à mon tableau "lettre", je prends la 1ère lettre disponible sur mon server local
For i = 0 To UBound(lettre)



    If Not fso.DriveExists(lettre(i)) Then 



       Call MapNetworkDrive(UCase(lettre(i) & ":"))



       Exit For



    End If

Next








 






Set WshShell = WScript.CreateObject("WScript.Shell")




ireturn = WshShell.Run("notepad " & resultat, 1, True)   'affiche mon fichier .txt









Set WshShell = Nothing



Set fso = Nothing




Set rapport = Nothing




WScript.Quit









Function MapNetworkDrive(lettre)



Dim WshNetwork




Set WshNetwork = WScript.CreateObject("WScript.Network")









'disks représente les drives que je souhaite mapper sur mon server distant 





Dim disks : disks = Array("C","D","E","F","G","I","J","K","L","M","N")



For i = 0 To UBound(disks)



result = ""



WshNetwork.MapNetworkDrive lettre, adressIP & disks(i) & "$", ,user,pssw




result = result &vbCrLf& "##########################################################################" &_




                       vbCrLf& libelle & adressIP & disks(i) & "$"










rapport.writeLine result & ShowFreeSpace(lettre,disks(i)) 









'ici je démappe la DriveLetter  de mon server local pour passer à mon disks(i) suivant






WshNetwork.RemoveNetworkDrive Lettre, True




Next









rapport.close




Set WshNetwork = Nothing




End Function









Function ShowFreeSpace(lettre,disque)



Dim fso, d, s



Set fso = CreateObject("Scripting.FileSystemObject")



Set d = fso.GetDrive(fso.GetDriveName(lettre))



s = " - Disk " & UCase(disque) & " - "



s = s & d.VolumeName



s = s &vbCrLf& "##########################################################################"_



         &vbCrLf& "Espace disponible (Free Space): " & FormatNumber(d.FreeSpace/1024, 0)



s = s & " Koctets"



librenum = d.FreeSpace



libre = okomogo(librenum)



totalnum = d.TotalSize



pourcentage = (Round(librenum / totalnum, 2) * 100)



contrepourcentage = 100 - pourcentage



hd = round(totalnum - librenum,4)



total = okomogo(totalnum)



s = s &vbCrLf& "Ce lecteur dispose de " & libre & " libres sur " &_




        total & " (soit " & VerifPourcent(pourcentage) & vbCrLf




If (hd > 0) Then s = s & okomogo(hd) & " sont déjà occupés (soit " & 




CStr(contrepourcentage) & " %)" 



ShowFreeSpace = s




'MsgBox ShowFreeSpace,,"verif ShowFreeSpace"




End Function









Function VerifPourcent(pourcentage)



'MsgBox pourcentage,,"verif pourcentage"



If CStr(pourcentage) <= 10 Then



   VerifPourcent CStr(pourcentage) & "%)  ALERTE FREE SPACE inférieur ou égal à 10%> ouvrir PAC"



Else



   VerifPourcent = CStr(pourcentage) & "%)"




End If




End Function










 





Function okomogo(brut)



kilo = 1024



mega = kilo * 1024



giga = mega * 1024



If brut > kilo Then



   If brut < mega Then



      fin = Round(brut / kilo, 3)



      okomogo = CStr(fin) & " Ko"



      Else



      If brut > giga Then



         fin = Round(brut / giga, 3)



         okomogo = CStr(fin) & " Go"



         Else



         fin = Round(brut / mega, 2)



         okomogo = CStr(fin) & " Mo"



       End If



   End If



Else



   okomogo = CStr(brut) + " octets"




End If




End Function










 



Si depuis hier, je n'ai pas répondu à tes questions, c'est qu'il y a un "gros" malentendu !!!
Espérant que ces explications ne soient pas trop soporifiques.   ça me fait bailler....
Il faut que je me force à arrêter de polluer "VBFrance" avec tous mes exemples répétitifs.

On en revient toujours à l'essentiel c-à-d. un bon énoncé dès le début du topic.

@+.
jean-marc
3
jmfmarques Messages postés 7666 Date d'inscription samedi 5 novembre 2005 Statut Membre Dernière intervention 22 août 2014 27
15 déc. 2006 à 21:53
C'est quoi ColDrives ? Une collection ?

Si oui, elle ne peut être un NULL !
Elle a par contre une propriété Count ...
0
cs_JMO Messages postés 1854 Date d'inscription jeudi 23 mai 2002 Statut Membre Dernière intervention 24 juin 2018 27
15 déc. 2006 à 21:58
 Bonsoir

   Dim fso, d, dc, s, n
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set dc = fso.Drives
   MsgBox dc.Count,,"Nombre de drives"
   For Each d in dc

jean-marc
0
mortalino Messages postés 6786 Date d'inscription vendredi 16 décembre 2005 Statut Membre Dernière intervention 21 décembre 2011 18
15 déc. 2006 à 21:59
Etant un objet, peut-être
If ton_objet <> Nothing Then

@++

<hr width="100%" size="2" />
  --Mortalino--
Le mystérieux chevalier, "Provençal, le Gaulois"
/DIV>
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
cs_JMO Messages postés 1854 Date d'inscription jeudi 23 mai 2002 Statut Membre Dernière intervention 24 juin 2018 27
15 déc. 2006 à 22:00
 Re,

Excuse-moi jmfmarques, je m'étais assoupi dans mes scripts.

jean-marc
0
leSaleGauSS Messages postés 148 Date d'inscription samedi 4 novembre 2006 Statut Membre Dernière intervention 4 décembre 2008
15 déc. 2006 à 22:05
For Each objDrive in colDrives
    msgbox colDrives.count
Next

Il passe pas dans la boucle (a moins que je me suis trompé dans la syntaxe?!)

Quand je suis là tout va mal  
0
cs_JMO Messages postés 1854 Date d'inscription jeudi 23 mai 2002 Statut Membre Dernière intervention 24 juin 2018 27
15 déc. 2006 à 22:09
Re,

Pourquoi mettre le msgbox dans la boucle.
Ce n'est pas mon exemple.

If dc.Count <>  0 Then
For Each ...
Next
End If

Sinon, il y a aussi la méthode IsObject

jean-marc
0
leSaleGauSS Messages postés 148 Date d'inscription samedi 4 novembre 2006 Statut Membre Dernière intervention 4 décembre 2008
15 déc. 2006 à 22:14
Oula j'ai oublié de rafraichir ...
615490 jmfmarques >> ma réponse est au dessus
=647037 mortalino >> déjà essayé ...
9517 JMO >> en  fait voila une partie du script peut-être que tu comprendras ...

Set objWMIService = GetObject("winmgmts:{impersonationLevel= impersonate}!\\.\root\cimv2")
'Quelles sont les lecteurs réseaux de l'utilisateur ?Set colDrives <gras>objWMIService.ExecQuery ("Select * From Win32_LogicalDisk Where DriveType</gras> 4")
For Each objDrive in colDrives
     CreateNetworkDrive    'Là c'est une fonction
Next

Voila en gros mon code. Arrivé au for each il va directement vers Next

Quand je suis là tout va mal  
0
jmfmarques Messages postés 7666 Date d'inscription samedi 5 novembre 2005 Statut Membre Dernière intervention 22 août 2014 27
15 déc. 2006 à 22:18
jmfmarques >> ma réponse est au dessus

Tu rigoles, ou quoi ?
So tu visualises le count dans ta boucle, c'est déjà trop tard si ta collection est vide

J'ai trop bu ? (crois pas !)

Allez !

Bonne nuit.
0
leSaleGauSS Messages postés 148 Date d'inscription samedi 4 novembre 2006 Statut Membre Dernière intervention 4 décembre 2008
15 déc. 2006 à 22:22
Oups sorry, jmfmarques, les joies du direct ...

Quand je suis là tout va mal  
0
cs_JMO Messages postés 1854 Date d'inscription jeudi 23 mai 2002 Statut Membre Dernière intervention 24 juin 2018 27
15 déc. 2006 à 22:23
 Re,

Set objSWbemServices = GetObject("winmgmts:")
Set colSWbemObjectSet = objSWbemServices.InstancesOf("Win32_LogicalDisk")
Set colSWbemObjectSet = GetObject("winmgmts:").InstancesOf("Win32_LogicalDisk")
For Each objDisk In GetObject("winmgmts:").InstancesOf("Win32_LogicalDisk")
    q =  q & vbCrLf& objDisk.DeviceID
Next

....jean-marc
0
leSaleGauSS Messages postés 148 Date d'inscription samedi 4 novembre 2006 Statut Membre Dernière intervention 4 décembre 2008
15 déc. 2006 à 22:32
Wbem ... ok je teste et je te dirai ou j'en suis

Quand je suis là tout va mal  
0
cs_JMO Messages postés 1854 Date d'inscription jeudi 23 mai 2002 Statut Membre Dernière intervention 24 juin 2018 27
15 déc. 2006 à 22:38
 Re,

Attention, comme tu testes un lecteur CD-Rom, il faut que ceui-ci soit ready.

If d.DriveType = 4 And d.IsReady Then

jean-marc
0
cs_JMO Messages postés 1854 Date d'inscription jeudi 23 mai 2002 Statut Membre Dernière intervention 24 juin 2018 27
15 déc. 2006 à 22:53
 Re,

ou

On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_CDROMDrive",,48)


For Each objItem in colItems
....

jean-marc
0
leSaleGauSS Messages postés 148 Date d'inscription samedi 4 novembre 2006 Statut Membre Dernière intervention 4 décembre 2008
15 déc. 2006 à 23:04
Ton code fonctionne (trop ?) bien ...

Est-ce qu'on peut faire un FileExists sur un lecteur réseau ?
Quand je suis là tout va mal  
0
leSaleGauSS Messages postés 148 Date d'inscription samedi 4 novembre 2006 Statut Membre Dernière intervention 4 décembre 2008
15 déc. 2006 à 23:08
Oublie mon message (j'ai du mal avec le refresh). En fait je doit juste gérer les lecteurs réseaux ...
@ ++

Quand je suis là tout va mal  
0
cs_JMO Messages postés 1854 Date d'inscription jeudi 23 mai 2002 Statut Membre Dernière intervention 24 juin 2018 27
15 déc. 2006 à 23:12
 Re,

Propriétés de Win32_CDROMDrive en WMI.

For Each objItem in colItems
 WScript.Echo "Availability: " & objItem.Availability
 WScript.Echo "Capabilities: " & objItem.Capabilities
 WScript.Echo "CapabilityDescriptions: " & objItem.CapabilityDescriptions
 WScript.Echo "Caption: " & objItem.Caption
 WScript.Echo "CompressionMethod: " & objItem.CompressionMethod
 WScript.Echo "ConfigManagerErrorCode: " & objItem.ConfigManagerErrorCode
 WScript.Echo "ConfigManagerUserConfig: " & objItem.ConfigManagerUserConfig
 WScript.Echo "CreationClassName: " & objItem.CreationClassName
 WScript.Echo "DefaultBlockSize: " & objItem.DefaultBlockSize
 WScript.Echo "Description: " & objItem.Description
 WScript.Echo "DeviceID: " & objItem.DeviceID
 WScript.Echo "Drive: " & objItem.Drive
 WScript.Echo "DriveIntegrity: " & objItem.DriveIntegrity
 WScript.Echo "ErrorCleared: " & objItem.ErrorCleared
 WScript.Echo "ErrorDescription: " & objItem.ErrorDescription
 WScript.Echo "ErrorMethodology: " & objItem.ErrorMethodology
 WScript.Echo "FileSystemFlags: " & objItem.FileSystemFlags
 WScript.Echo "FileSystemFlagsEx: " & objItem.FileSystemFlagsEx
 WScript.Echo "Id: " & objItem.Id
 WScript.Echo "InstallDate: " & objItem.InstallDate
 WScript.Echo "LastErrorCode: " & objItem.LastErrorCode
 WScript.Echo "Manufacturer: " & objItem.Manufacturer
 WScript.Echo "MaxBlockSize: " & objItem.MaxBlockSize
 WScript.Echo "MaximumComponentLength: " & objItem.MaximumComponentLength
 WScript.Echo "MaxMediaSize: " & objItem.MaxMediaSize
 WScript.Echo "MediaLoaded: " & objItem.MediaLoaded
 WScript.Echo "MediaType: " & objItem.MediaType
 WScript.Echo "MfrAssignedRevisionLevel: " & objItem.MfrAssignedRevisionLevel
 WScript.Echo "MinBlockSize: " & objItem.MinBlockSize
 WScript.Echo "Name: " & objItem.Name
 WScript.Echo "NeedsCleaning: " & objItem.NeedsCleaning
 WScript.Echo "NumberOfMediaSupported: " & objItem.NumberOfMediaSupported
 WScript.Echo "PNPDeviceID: " & objItem.PNPDeviceID
 WScript.Echo "PowerManagementCapabilities: " & objItem.PowerManagementCapabilities
 WScript.Echo "PowerManagementSupported: " & objItem.PowerManagementSupported
 WScript.Echo "RevisionLevel: " & objItem.RevisionLevel
 WScript.Echo "SCSIBus: " & objItem.SCSIBus
 WScript.Echo "SCSILogicalUnit: " & objItem.SCSILogicalUnit
 WScript.Echo "SCSIPort: " & objItem.SCSIPort
 WScript.Echo "SCSITargetId: " & objItem.SCSITargetId
 WScript.Echo "Size: " & objItem.Size
 WScript.Echo "Status: " & objItem.Status
 WScript.Echo "StatusInfo: " & objItem.StatusInfo
 WScript.Echo "SystemCreationClassName: " & objItem.SystemCreationClassName
 WScript.Echo "SystemName: " & objItem.SystemName
 WScript.Echo "TransferRate: " & objItem.TransferRate
 WScript.Echo "VolumeName: " & objItem.VolumeName
 WScript.Echo "VolumeSerialNumber: " & objItem.VolumeSerialNumber
 WScript.Echo ""
Next

jean-marc
0
leSaleGauSS Messages postés 148 Date d'inscription samedi 4 novembre 2006 Statut Membre Dernière intervention 4 décembre 2008
16 déc. 2006 à 01:53
0
leSaleGauSS Messages postés 148 Date d'inscription samedi 4 novembre 2006 Statut Membre Dernière intervention 4 décembre 2008
16 déc. 2006 à 01:56
ben pourquoi mon message c'est effacer ?
0
leSaleGauSS Messages postés 148 Date d'inscription samedi 4 novembre 2006 Statut Membre Dernière intervention 4 décembre 2008
16 déc. 2006 à 02:02
Set objSWbemServices = GetObject("winmgmts:")
Set colSWbemObjectSet = objSWbemServices.InstancesOf("Win32_LogicalDisk")
Set colSWbemObjectSet = GetObject("winmgmts:").InstancesOf("Win32_LogicalDisk")
set f=fso.opentextfile(sFile_Current)
do while not f.AtEndOfStream
 TabListe = split(f.readLine, ";")
 bVerif=False
 For Each objGroup in objmemberOf
  'appel de la fonction Groupe
  sService=SubGroupe(objGroup)
  select case sArgument
   ...
   case "NetworkDrive"
   If TabListe(NetworkDrive_State)="enable" then
    For Each objDrive In GetObject("winmgmts:").InstancesOf("Win32_LogicalDisk")
    if objDrive.DeviceID<>TabListe(sNetworkDrive_Letter) then
    msgbox objDrive.DeviceID &" <> "& TabListe(NetworkDrive_Letter)
     CreateNetworkDrive TabListe(NetworkDrive_Letter), TabListe(NetworkDrive_Path), TabListe(NetworkDrive_Update)
     bVerif=True
     exit for
    end if
    Next     
   end if
  End select
 next
 ...
 If sArgument="NetworkDrive" then
  For Each objDrive in colDrives
    if bVerif=False then
     deleteNetworkDrive TabListe(sNetworkdrive_Letter)
    end if
  Next
 End if
loop
f.close


sub CreateNetworkDrive (sNetworkDrive_Letter , sNetworkDrive_Path, sNetworkDrive_Update)
LogFile.writeLine(now &" Création de "& sNetworkDrive_Path)'Ecriture dans fichier log
 net.MapNetworkDrive sNetworkDrive_Letter , sNetworkDrive_Path, sNetworkDrive_Update
end sub


sub DeleteNetworkDrive (sNetworkDrive_Letter)
LogFile.writeLine(now & " Suppression de "&sNetworkDrive_Letter)'%%%%%
 'Suppression du lecteur réseau
 net.RemoveNetWorkDrive sNetworkDrive_Letter
end sub



Quand je suis là tout va mal  
0
Rejoignez-nous