VBS: Permission denied when deleting a file or a folder - vbscript

This is my code, which first checks for a folder which contains the installer, if found, runs the uninstall and deletes the uninstall.exe if it still exists. Lastly, it deletes the folder itself.
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set wshshell = wscript.CreateObject("WScript.Shell")
If objFSO.FolderExists("C:\Installer_3_00_00") Then
Set objFolder = objFSO.GetFolder("C:\Installer_3_00_00")
if objFSO.FileExists("C:\Installer_3_00_00\uninstall.exe") Then
Wshshell.run "C:\Installer_3_00_00\uninstall.exe -q"
End if
if objFSO.FileExists("C:\Installer_3_00_00\uninstall.exe") Then
Set objFile=objFSO.GetFile("C:\Installer_3_00_00\uninstall.exe")
objFile.Delete True
End if
objFolder.Delete True
Else
End If
Set objFSO = Nothing
The problem is: It says Permission denied trying to delete a file or folder. I cross checked by deleting manually and it worked. I have searched for similar problems in this forum but none of which helped me to solve this particular issue.
Any suggestions will be appreciated.
Thanks
P.s I tried formatting my code here, but still I was not able to format it correctly.

Your problem is most likely caused by the (un)installer still running when you try to delete it, because this call:
Wshshell.run "C:\Installer_3_00_00\uninstall.exe -q"
returns immediately without waiting for the program to finish. Change that line into this:
Wshshell.Run "C:\Installer_3_00_00\uninstall.exe -q", 0, True

Related

File checking on Windows Startup is failing [duplicate]

This question already has answers here:
Getting current directory in VBScript
(9 answers)
Cannot get the current directory in .vbs file [duplicate]
(1 answer)
Closed 2 years ago.
I have this script that allows me to automatically backup my MySQL Database every 5 minutes using a batch file.
Dim WshShell
Dim FSO
Dim stopBackup
stopBackup = false
' Register on Windows Startup if not registered when this file is opened.
RegisterOnWindowsStartUp()
' Keep backing up the database every 5 minutes, loop will do.
Do While True
Set FSO = CreateObject("Scripting.FileSystemObject")
If fso.FileExists("auto_backup.bat") Then ' Check if bat file for backing up the database exist.
MsgBox "Backup Message Test."
' Run the batch file which handle the auto backup of database, keep it invisible.
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "auto_backup.bat" & Chr(34), 0
Set WshShell = Nothing
WScript.Sleep 300000 ' Delay loop every 5 minutes.
Else ' Stop the loop and do not proceed anymore when the bat file is not exist.
WScript.Echo "Failed to auto backup the database, this won't continue anymore."
stopBackup = true
RemoveFromRegistry() ' Unregister this file on Windows Startup since the bat file is no longer exist.
End If
If stopBackup Then ' Break the loop when stopBackup become true
Exit Do ' Break the loop here.
End If
Loop
' Remove this script from registry on Windows Startup
Function RemoveFromRegistry()
Set objShell = Wscript.CreateObject("Wscript.Shell")
objShell.RegDelete "HKCU\Software\Microsoft\Windows\CurrentVersion\Run\autobackup_key"
End Function
' Register this script on Windows Startup only if not registered.
Function RegisterOnWindowsStartUp()
If IsRegistryExist = False Then
Set WshShell = CreateObject("WScript.Shell")
keyNameLocation = "HKCU\Software\Microsoft\Windows\CurrentVersion\Run\autobackup_key"
valueFileLocation = WScript.ScriptFullName
keyType = "REG_SZ"
WshShell.RegWrite keyNameLocation, valueFileLocation, keyType
Set WshShell = Nothing
End If
End Function
' Check if Registry Key Exist on Windows Startup.
Function IsRegistryExist()
Dim sKey, bFound
skey = "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\autobackup_key"
with CreateObject("WScript.Shell")
on error resume next ' turn off error trapping
sValue = .regread(sKey) ' read attempt
bFound = (err.number = 0) ' test for success
on error goto 0 ' restore error trapping
end with
If bFound Then
IsRegistryExist = True
Else
IsRegistryExist = False
End If
End Function
The filename of the batch file that allows me to back up the database is auto_backup.bat and it's working fine and no problem, it's on the same directory where the script above is located.
The problem is every time the Windows Startup, it fails to check for the existence of auto_backup.bat, but when I open the script and run it, its working fine and no issue.
There might be some issue with my logic, can anybody help me fix it?
it's on the same directory where the script above is located
This is not where a relative path looks. It starts from the working directory.
The working directory of a shortcut is not necessarily the directory containing the shortcut. You should edit the shortcut properties and set the working directory you want, instead of using the default (which is often C:\Windows or C:\Users\%USERNAME%)
Or you can put an absolute path in the script, or have the script change working directory to its own directory, or have the script combine its directory and the filename to dynamically create an absolute path.
The problem is because when you register your script on Windows Startup through the registry, the script will be executed from the directory of Windows Startup when windows started.
In order to get the original working directory where you can look for the auto_backup.bat, you can combine the FileSystemObject and WScript.ScriptFullName functions to get the parent directory of the current script.
CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName) & "\auto_backup.bat"
Then the IF-ELSE condition inside your loop would be
...
Do While True
Set FSO = CreateObject("Scripting.FileSystemObject")
' (1) Add this code.
autobackup_bat_file = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName) & "\auto_backup.bat"
If fso.FileExists(autobackup_bat_file) Then ' (2) Change this line.
MsgBox "Backup Message Test."
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & autobackup_bat_file & Chr(34), 0 ' (3) Change this line.
' Continue some of your code here...
...

Script to remove shortcuts won't work with version numbers

I'm running a vbscript to remove desktop shortcuts installed by another program, the problem I have though is one shortcut is being stubborn
set WshShell = WScript.CreateObject("WScript.Shell" )
strDesktop = WshShell.SpecialFolders("Desktop" )
' delete this shortcut
strShortcut = strDesktop & "\Shortcut Name 2.0.lnk"
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(strShortcut) Then fso.DeleteFile(strShortcut)
I have a feeling it's to do with the version number and decimal point in-between? Can anyone confirm my suspicion as I'm completely out of clues.
Thanks.
The file you want to delete probably doesn't already exist, If fso.FileExists(strShortcut) Then masks that fact.
A shortcut you see in your desktop doesn't have to be in your Desktop folder that you acquired with WshShell.SpecialFolders("Desktop").
There is another location where desktop items are stored as an extension to the all users' desktop directories, but may require administrative privileges to modify, I'm not sure, you need to try.
So, in addition to SpecialFolders("Desktop"), you should also consider the SpecialFolders("AllUsersDesktop") directory.
Set Fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
userDesktop = WshShell.SpecialFolders("Desktop")
publicDesktop = WshShell.SpecialFolders("AllUsersDesktop")
shortcutName = "Shortcut Name 2.0.lnk"
userShortcut = Fso.BuildPath(userDesktop, shortcutName)
publicShortcut = Fso.BuildPath(publicDesktop, shortcutName)
If Fso.FileExists(userShortcut) Then
Fso.DeleteFile userShortcut, True
MsgBox "User shortcut deleted."
End If
If Fso.FileExists(publicShortcut) Then
Fso.DeleteFile publicShortcut, True
MsgBox "Public shortcut deleted."
End If

File wont move to folder vbs

So im writing a script that drops a file folder then moves that file to the folder it dropped it self. Well the folder drops fine but the file wont move. Can some see whats wrong with my code? Or give me a better way to move the file. I also get no error message about trying to move the file.
Dim folder,fso,filsys,C
Set fso = CreateObject("Scripting.filesystemObject")
Set folder = fso.GetSpecialFolder(1)
Set wshshell = CreateObject("wscript.shell")
Set filesys = CreateObject("scripting.filesystemobject")
Set objfso = CreateObject("Scripting.filesystemObject")
Set c = fso.GetFile(Wscript.scriptFullname)
On Error Resume NEXT
Set objFolder = objFSO.CreateFolder("C:\55egr932ntn7mk23n124kv1053bmoss5")
If Err.Number<>0 Then
End If
WScript.Sleep 3000
C.Move ("C:\552ntn7mk23n124kv1053bmoss5\File.exe") (folder&"\File.exe")
And I have a program I use that turns the VBS into and EXE so you see the "file.exe" which really is the .VBS itself
I'm not familiar with this syntax, but the line below looks like it's expecting the folder variable to be a string.
C.Move ("C:\552ntn7mk23n124kv1053bmoss5\File.exe") (folder&"\File.exe")
Earlier in code it looks as though you're setting folder as an object.
Set folder = fso.GetSpecialFolder(1)
You might not get the error you mentioned in your comment if you convert folder to a string.
~~
Another thing to try is the following code:
Set fso = CreateObject("Scripting.filesystemObject")
Set folder = fso.GetSpecialFolder(1)
Alert (folder&"\File.exe")
(I'm not sure if it's "Alert" or "Msgbox" or something else.) That test will show you whether the file path makes sense. If you get an error on line 3 of that test, try converting folder to a string before your Alert (or Msgbox).

Renaming files in a loop - permission denied or the object invoked has disconnected from its clients errors

I am trying to include a renaming function to a loop which opens Word files and looks for tracked changes - if there are Tracked changes, I want to rename the file to get a _tracked_changes_ prefix.
However, I encounter a problem - I get a permission denied error, I am assuming because the file is open when I am trying to rename it. However, when I include the objFile.close function, the "object invoked has disconnected from its clients". I don't know how can I keep the reference of the objFile variable to the file I am processing and bypass the "permission denied" problem.
The code is:
Set fso = CreateObject("Scripting.FileSystemObject")
Set app = CreateObject("Word.Application")
app.Visible = false
app.DisplayAlerts = true
For Each objFile In fso.GetFolder(".").Files
If Lcase(fso.GetExtensionName(objFile)) = "docx" Then
<<<subprocedure that checks for tracked changes>>>
set objFile = app.Documents.Open(objFile.Path)
objFile.Name = "_tracked_changes_" & objfile.name
'Call check_tc
End If
Next
This naturally works fine if I don't have the set objFile = app.Documents.Open(objFile.Path) element, but I have to open the file to see if it has tracked changes.
First, change the set objFile = app.Documents.Open(objFile.Path) to something else besides objFile, as this is reusing the first objFile and that'd be why you're getting the disconnected error.
Then you should be able to close it.
So
set objWord = app.Documents.Open(objFile.Path)
objWord.close
Then
objFile.Name = "_tracked_changes_" & objfile.name

how to access a network folder using vbscript

I have a folder which is on a network like \\server\contents\tasks and I want to access this folder.
I am getting a "path not found" exception. What am I doing wrong here:
Dim FolderPath
FolderPath = "\\server\contents\tasks"
set FSO = CreateObject("Scripting.FileSyatemObject")
FSO.GetFolder(FolderPath)
Thanks
Edit: I found this post which answers the same thing I am trying to achieve, but the issue is I am getting an error the network share is no longer available. What I have is a local folder as a shared folder and mapped as \\servername\contents\tasks but it gives me the above error.
Edit: I was pointing at the wrong folder.
Now I have another issue trying to open a text file in the network folder. It is able to create a folder at the network path but throwing error while reading a text file in the network folder. Is there something else that needs to be done?
Set FSO = CreateObject("Scripting.FileSystemObject")
strOutputPath = strOutput1 --this is a network path
Set txsOutput = FSO.CreateTextFile(strOutputPath)
Set f = FSO.OpenTextFile(strInput1)
Open the network folder using explorer.exe and pass the location of the folder as a parameter (in this example it's sPath storing the folder path)
Example:
sPath = "\\somedrive.somecompany.ie\software"
Set oShell = CreateObject("WScript.Shell")
oShell.Run "explorer /n," & sPath, 1, False
Terms and conditions: username and password privileges already setup for acccess to the network folder.

Resources