2

I create a .vbs file (that can: creat text file -> Open notepad.exe -> delete the file above) like this:

' Create a new file
Dim objFS, objFile
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.CreateTextFile("D:\Folder\Textfile.txt")
objFile.WriteLine ("sample text")

' Run a program and wait
WScript.CreateObject("WScript.Shell").Run "notepad.exe", 1, true

' Delete file
objFS.Deletefile("D:\Folder\Textfile.txt")

But when I run it, after close notepad window, it show error message:

Line: 10
Char: 1
Error: Permission denied
Code: 800A0046
Source: Microsoft VBScript runtime error

I don't know why this .vbs can't not delete the text file? Thank you for any help!

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Baeb
  • 21
  • 1
  • 1
  • 2

1 Answers1

6

You have to close the file handle in the script before trying to delete it.

' Create a new file
Dim objFS, objFile
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.CreateTextFile("D:\Folder\Textfile.txt")

'write to the file
objFile.WriteLine ("sample text")

'close the file
objFile.close
set objFile = Nothing

' open the file in notepad, and wait
WScript.CreateObject("WScript.Shell").Run "notepad.exe D:\Folder\Textfile.txt", 1, true

' Delete file
objFS.Deletefile("D:\Folder\Textfile.txt")

set objFS = Nothing
Flakes
  • 2,422
  • 8
  • 28
  • 32
  • That worked perfectly! Thank you very much, BTW, can you tell me where to learn the script above and some useful thing about VBS? – Baeb Aug 03 '15 at 12:59
  • you could check this: [VBScript Fundamentals](https://msdn.microsoft.com/en-us/library/0ad0dkea.aspx), also check other sections in msdn – Flakes Aug 03 '15 at 13:07