vbscript reads File object properties, but won't delete the file

1.5k views Asked by At

Here is my (very simple) code:

if fs.FileExists(strPath) then
    set thisFile=fs.GetFile(strPath)
    wscript.echo thisFile.Name & " (" & thisFile.Size & ") will be deleted" 
    thisFile.Delete
end if

The path is correct, because I can read the file name and file size in the output. However, this is the output I'm getting:

D:\Inetpub>cscript PDFDelete.vbs

Microsoft (R) Windows Script Host Version 5.8

Copyright (C) Microsoft Corporation. All rights reserved.

131_1443_cds101711.pdf (28660) will be deleted

D:\Inetpub\PDFDelete.vbs(38, 3) Microsoft VBScript runtime error: File not found

As you can see, I get the proper output on the file properties, so I know I have a valid reference to the file object, but trying to execute the Delete() method on that exact same file object produces a "File not found" error?!

It makes no sense to me. How can the file be "not found" if I just accessed its name and size properties?

EDIT I should have mentioned, I initially was using the code "fs.DeleteFile(strPath)" when I first got the "File Not Found" error. I changed it to the more direct "File.Delete()" method, but the error persists.

2

There are 2 answers

1
Nathan Rice On

You can try:

if fs.FileExists(strPath) then
  set thisFile=fs.GetFile(strPath)
  wscript.echo thisFile.Name & " (" & thisFile.Size & ") will be deleted" 
  fs.DeleteFile strPath
end if

http://www.devguru.com/technologies/vbscript/14055

2
JMax2012 On

I found the issue.

There was a stray line of code further down in the script that was referencing thisFile.Size, after trying to delete that file. The error was happening on that line, not on the thisFile.Delete line.

Moral of the story: make use of the On Error Resume Next/On Error Goto 0 error trapping from the start, and things get a lot clearer.