Search code examples
vbscriptaccess-deniedfilesystemobject

Why I can't delete a folder in "program files"?


I run the follow script with admin rights:

Dim FSO
Set FSO = WScript.CreateObject("Scripting.FileSystemObject")

Dim tempName, fullTempName, tempFolder
tempName = FSO.GetTempName
fullTempName = "c:\program files\" + tempName
Set tempFolder = fso.CreateFolder( fullTempName )
tempFolder.Attributes = 0
tempFolder.Delete( True )

I can create the folder but I can't delete it. I receive the error message:

Microsoft VBScript runtime error: Permission denied.

translated from German:

Laufzeitfehler in Microsoft VBScript: Erlaubnis verweigert.

The reseting of the attributes has no effect. It is continue 16 (read-only). Why this error occur and how can I resolve it?


Solution

  • I found the follow workaround. I replace the line of "tempFolder.Delete" with:

    Dim wshShell
    Set wshShell = CreateObject("WScript.Shell")
    wshShell.Run wshShell.ExpandEnvironmentStrings( "%SystemRoot%\system32\cmd.exe /c rd """ & fullTempName & """" ), 0