Solved

VBScript and WMI Need to delete Folder/Files under the parent directory How to?

Posted on 2006-06-28
9
1,232 Views
Last Modified: 2009-12-16
Hi,

  I need to delete files and folders under a directory but keep the base.  I have tried FSO Example
Set FSO = CreateObject("Scripting.FileSystemObject")
FSO.DeleteFolder "D:\test\*", True
FSO.DeleteFile "D:\test\*", True

But if a file/directory is open or can not be removed the script stops and ends.  From what I can tell I will have to use WMI in the script and enumerate.  I am a total newbie!! and dont have a clue.  What I want to do is

1) Delete all files and subdirectories under \\<sharename>\TEST\ but not TEST itself
2) If a file or folder is open and locked skip that file/folder and continue (FSO can NOT do this)
3)  Pass a error level back.  

If someone can give me a working example it really would be great!!!!

Thanks !
0
Comment
Question by:alttechnology
  • 4
  • 3
9 Comments
 
LVL 3

Assisted Solution

by:gafoorgk
gafoorgk earned 500 total points
ID: 17006967
follow this code or take it as a template for your need. if file or folder could not be delete for some reason, it's logged and returned.


Option Explicit

Private Sub Command1_Click()
    Debug.Print DeleteAll("\\<sharename>\TEST")
End Sub

Private Function DeleteAll(strFolder As String) As String
    Dim fso As Scripting.FileSystemObject
    Dim objFile As Scripting.File
    Dim objFolder As Scripting.Folder
    Dim strLog As String
   
    '// Create new file system object
    Set fso = New Scripting.FileSystemObject
   
    On Error Resume Next
   
    '// First delete all files
    For Each objFile In fso.GetFolder(strFolder).Files
        objFile.Delete True
        '// If errors occured
        If (Err.Number > 0) Then
            strLog = strLog & "File " & objFile.Path & " could not be deleted." & vbCrLf
            Err.Clear
        End If
    Next
   
    '// Then delete all folders
    For Each objFolder In fso.GetFolder(strFolder).SubFolders
        objFolder.Delete (True)
        '// If errors occured
        If (Err.Number > 0) Then
            strLog = strLog & "Folder " & objFolder.Path & " could not be deleted." & vbCrLf
            Err.Clear
        End If
    Next
   
    '// Finally return the log
    DeleteAll = strLog
   
    '// Clear objects
    Set fso = Nothing
End Function
0
 

Author Comment

by:alttechnology
ID: 17014716
I know that I have very limited experience but, I think I understand most of this.  I do error on the Private Function line.  Is that syntax correct?  I get the error looking for the end the statement.   I do not know the correct line.  Can you help  Thanks !

 
0
 
LVL 3

Expert Comment

by:gafoorgk
ID: 17022331
i didn't understand u. can u explain in detail ?!
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

Author Comment

by:alttechnology
ID: 17023867
Sure,
I am sure this is a simple fix but, I get an error on
Function DeleteAll(strFolder As String) As String
Error VBScript compilation error: Expected ')'

0
 
LVL 3

Accepted Solution

by:
gafoorgk earned 500 total points
ID: 17025621
ah sorry. actually the code was not tested the line 'objFolder.Delete (True)' caused the error. following code is corrected.

Option Explicit

Private Sub Command1_Click()
    Debug.Print DeleteAll("C:\Documents and Settings\gafoorgk\Desktop\New Folder")
End Sub

Private Function DeleteAll(strFolder As String) As String
    Dim fso As Scripting.FileSystemObject
    Dim objFile As Scripting.File
    Dim objFolder As Scripting.Folder
    Dim strLog As String
   
    '// Create new file system object
    Set fso = New Scripting.FileSystemObject
   
    On Error Resume Next
   
    '// First delete all files
    For Each objFile In fso.GetFolder(strFolder).Files
        objFile.Delete True
        '// If errors occured
        If (Err.Number > 0) Then
            strLog = strLog & "File " & objFile.Path & " could not be deleted." & vbCrLf
            Err.Clear
        End If
    Next
   
    '// Then delete all folders
    For Each objFolder In fso.GetFolder(strFolder).SubFolders
        objFolder.Delete True
        '// If errors occured
        If (Err.Number > 0) Then
            strLog = strLog & "Folder " & objFolder.Path & " could not be deleted." & vbCrLf
            Err.Clear
        End If
    Next
   
    '// Finally return the log
    DeleteAll = strLog
   
    '// Clear objects
    Set fso = Nothing
End Function
0
 

Author Comment

by:alttechnology
ID: 17091627

Sorry for not responding sooner.  I was on vacation.  I just tested the script and I get the following error.  I jsut did a cut and paste and it errors on

Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

D:\Scripts\newdelfiles.vbs(7, 38) Microsoft VBScript compilation error: Expected
 ')'

Hhmm...  I just ran it in VBSEdit and it does not like the
Private Function DeleteAll(strFolder As String) As String

I am testing this on a Windows XP WS.  Sorry for not being able to dubug this further...

Thanks Al
0
 

Author Comment

by:alttechnology
ID: 17092948
gafoorgk,  Here is one that works quite well.  The only issue I have is if there is files in the root it does not like that and errors with
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

c:\testlog\werec13.dir00Line 50
D:\Scripts\Thisisit.vbs(63, 5) (null): 0x80041002





Dim arrFolders()
intSize = 0

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

strFolderName = "c:\testlog"

Set colSubfolders = objWMIService.ExecQuery _
    ("Associators of {Win32_Directory.Name='" & strFolderName & "'} " _
        & "Where AssocClass = Win32_Subdirectory " _
            & "ResultRole = PartComponent")

ReDim Preserve arrFolders(intSize)
arrFolders(intSize) = strFolderName
intSize = intSize + 1

For Each objFolder in colSubfolders
    GetSubFolders strFolderName
Next

Sub GetSubFolders(strFolderName)
    Set colSubfolders2 = objWMIService.ExecQuery _
        ("Associators of {Win32_Directory.Name='" & strFolderName & "'} " _
            & "Where AssocClass = Win32_Subdirectory " _
                & "ResultRole = PartComponent")

    For Each objFolder2 in colSubfolders2
        strFolderName = objFolder2.Name
        ReDim Preserve arrFolders(intSize)
        arrFolders(intSize) = strFolderName
        intSize = intSize + 1
        GetSubFolders strFolderName
    Next
End Sub

For i = Ubound(arrFolders) to 1 Step -1
    strFolder = arrFolders(i)
    strFolder = Replace(strFolder, "\", "\\")
    Set colFolders = objWMIService.ExecQuery _
        ("Select * from Win32_Directory where Name = '" & strFolder & "'")

    For Each objFolder in colFolders
        errResults = objFolder.Delete
    Next
Next

'Now do the files in root of the directory

wscript.echo strFolderName & "Line 50"

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set colFileList = objWMIService.ExecQuery _
    ("ASSOCIATORS OF {Win32_Directory.Name='"& strFolderName & "'} Where " _
        & "ResultClass = CIM_DataFile")

'If colFileList.Count = 0 Then
'    Wscript.Echo "There were no files in the folder."
'Else
'    Wscript.Echo "There were " & colFileList.Count & " files in the folder."
'
    For Each objFile In colFileList
        objFile.Delete
    Next
'End If
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Article by: Martin
Here are a few simple, working, games that you can use as-is or as the basis for your own games. Tic-Tac-Toe This is one of the simplest of all games.   The game allows for a choice of who goes first and keeps track of the number of wins for…
Deploying a Microsoft Access application in a Citrix environment is not difficult but takes a few steps. However, Citrix system people are often of little help, as they typically know next to nothing about Access. The script provided here will take …
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now