Option Explicit
On Error Resume Next
Const MY_PICTURES = &H27
Const DeleteReadOnly = True
Dim fso, shell, folder, folderItem
Dim pathStr, filesStr, i
Set fso = CreateObject( "Scripting.FileSystemObject" )
Set shell = CreateObject( "Shell.Application" )
Set folder = shell.Namespace( MY_PICTURES )
Set folderItem = folder.Self
pathStr = folderItem.Path
filesStr = pathStr & "\*.txt"
fso.DeleteFile filesStr, DeleteReadOnly
we have a script that connects to the My Pictures folder and deletes any .txt files it finds there. As for the code itself, we start things off the On Error Resume Next statement. This statement is very important. In order to keep the script simple, we don’t bother verifying whether or not there actually are any .txt files in the My Pictures folder; we just have code that deletes those files. If it turns out that no such files exist, an error will be generated: without the On Error Resume Next statement, that error would cause the script to blow up. With this statement, however, the script simply shrugs its shoulders and keeps going. Next we define a pair of constants:
Const MY_PICTURES = &H27
Const DeleteReadOnly = True
MY_PICTURES assigned the value &H27; this is the value used by the Shell object to locate the My Pictures folder. Granted, we could simply hardcode in a path like this:
C:\Documents and Settings\usr01\My Documents\My Pictures
By using the Shell object and the MY_PICTURES constant, however, we can create a "generic" script that will work on any computer, regardless of the actual path to the My Pictures folder.
Meanwhile, the constant DeleteReadOnly tells the FileSystemObject to go ahead and delete any read-only files found in the My Pictures folder. This is also very important: if we leave this out then the script will crash if it encounters any read-only .txt. Next, we create instances of the Scripting.FileSystemObject and the Shell.Application objects. We use the Shell.Application object to determine the path to the My Pictures folder and store that path in a variable named pathStr; that’s what we do here:
Set folder = shell.Namespace( MY_PICTURES )
Set folderItem = folder.Self
pathStr = folderItem.Path
As you can see, we call the Namespace method, passing this method the constant MY_PICTURES ( which tells the Shell object which special folder to bind to ). In order to get the path to the folder, we call the Self method; this creates an object reference to the actual folder. Once we have that object reference ( folderItem ) we can then store the value of the Path property in the variable pathStr.
Based on "How Can I Auto-Delete Specific File Types from the My Pictures Folder?" from the Scripting Guys
Posted in FileSystemObject

daniva




Recent Comments