Reputation: 142
I am writing a simple script to delete all text files from "My Documents" directory. The script is working fine but after deleting the last file, it gives Permission Denied (Error Code: 800A0046). For example, if I have 3 .txt files in the directory, the error occurs after the 3rd file is deleted. I don't think it's a permission issue because in that case, no file would have been deleted. It's something very basic that I am missing. I have added a 1-second delay, which allows me to see the files getting deleted one after another. Here is the script:
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFolder = CreateObject("Wscript.Shell").specialfolders("MyDocuments")
Dim objFile
For each objFile in objFolder.Files
If LCase(objFSO.GetExtensionName(objFile.name)) = "txt" Then
objFSO.DeleteFile(objFile), True
Wscript.Sleep 1000
End If
Next
Upvotes: 1
Views: 497
Reputation: 18837
You should change this line to set the objFolder :
objFolder = CreateObject("Wscript.Shell").specialfolders("MyDocuments")
to
Set objFolder = objFSO.GetFolder(CreateObject("Wscript.Shell").SpecialFolders("MyDocuments"))
And here is a quick test to list all my text files in My Documents folder :
Option Explicit
Dim objFSO,objFile,objFolder,MyDoc,F
Set objFSO = CreateObject("Scripting.FileSystemObject")
MyDoc = CreateObject("Wscript.Shell").SpecialFolders("MyDocuments")
Set objFolder = objFSO.GetFolder(MyDoc)
For each objFile in objFolder.Files
If LCase(objFSO.GetExtensionName(objFile.name)) = "txt" Then
F = F & objFile & vbcrlf
End If
Next
wscript.echo F
Upvotes: 2