Permission denied on CopyFile in VBS - vbscript

I'm trying to automate pushing a file into my users' home directories, but am stuck on a "Permission Denied" error — is thrown on line 6 here, with the CopyFile call.
There are other parts of the script (not shown) that create and copy folder contents using the same source and destination directories, and they work perfectly. It's only when I use CopyFile that it fails.
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists("H:\Minecraft\.minecraft\options.txt") Then
fso.CopyFile "C:\Minecraft\options.txt", "H:\Minecraft\.minecraft\"
End If
Set fso = Nothing
H: is a network home directory, to which the current user has full read/write privs.
I've tried adding/removing trailing slashes from the paths, adding "options.txt" to the destination path, removing the false argument... Not sure what else to try. Any thoughts?
FYI, this chunk of code, which comes immediately before the error-prone bit above, executes perfectly every time:
If Not fso.FolderExists("H:\Minecraft\.minecraft\bin\") Then
If Not fso.FolderExists("H:\Minecraft\.minecraft\") Then
fso.CreateFolder("H:\Minecraft\.minecraft\")
End If
fso.GetFolder("C:\Minecraft\bin\").Copy "H:\Minecraft\.minecraft\"
End If

I've only ever seen CopyFile fail with a "permission denied" error in one of these 3 scenarios:
An actual permission problem with either source or destination.
Destination path is a folder, but does not have a trailing backslash.
Source file is locked by an application.

for me adding / worked at the end of location of folder.
Hence, if you are copying into folder, don't forget to put /

Based upon your source variable (sourcePath = "C:\Minecraft\bin\") I suspect your hard code is pointing at the wrong place
fso.CopyFile "C:\Minecraft\options.txt", destinationPath, false
should be
fso.CopyFile "C:\Minecraft\bin\options.txt", destinationPath
or
fso.CopyFile sourcePath & "options.txt", destinationPath

Another thing to check is if any applications still have a hold on the file.
Had some issues with MoveFile. Part of my permissions problem was that my script opens the file (in this case in Excel), makes a modification, closes it, then moves it to a "processed" folder.
In debugging a couple things, the script crashed a few times. Digging into the permission denied error I found that I had 4 instances of Excel running in the background because the script was never able to properly terminate the application due to said crashes. Apparently one of them still had a hold on the file and, thusly, "permission denied."

I have read your problem, And i had the same problem. But af ter i changed some, my problem "Permission Denied" is solved.
Private Sub Addi_Click()
'On Error Resume Next
'call ds
browsers ("false")
Call makeAdir
ffgg = "C:\Users\Backups\user\" & User & "1\data\"
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.Getfolder("c:\users\Backups\user\" & User & "1\data")
f.Attributes = 0
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Call fso.Copyfile(filetarget, ffgg, True)
Look at ffgg = "C:\Users\Backups\user\" & User & "1\data\", Before I changed it was ffgg = "C:\Users\Backups\user\" & User & "1\data" When i add backslash after "\data\", my problem is solved. Try to add back slash. Maybe solved your problem. Good luck.

You can do this:
fso.CopyFile "C:\Minecraft\options.txt", "H:\Minecraft\.minecraft\options.txt"
Include the filename in the folder that you copy to.

It's worth checking task manager for any stray wscript.exe tasks that are stuck.
It could be one of those that's blocking access to the file.

It is possible that your Antivirus software may be preventing the activity of the script. I encountered this with AVG Antivirus running in silent mode (which means it does not alert you to every protection step it takes, so you get a permission error without realising that AVG is preventing the action).
In my case, I invoked verbose mode (switched off silent mode), executed the script and AVG came up with an interception warning, allowing me to train AVG to permit this script to run.

Related

Srcipt vbs, moveFolder return Permission denied

Option Explicit
dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FolderExists("C:\Users\michal\Desktop\mv_files_backup") then
fso.MoveFolder "C:\Users\michal.glowacki\Desktop\mv_files_backup\*.*", "\\192.168.10.245\backup\servers\backup_server"
Else
wscript.echo "doesn't exist"
End If
When I try run this script I have error:
Permission denied 800A0046
but when I change MoveFolder to CopyFolder script works correctly. Why I can't use function MoveFolder ?
From MSDN:
If source contains wildcards or destination ends with a path separator
( \ ), it is assumed that destination specifies an existing folder in
which to move the matching files. Otherwise, destination is assumed to
be the name of a destination folder to create. In either case, three
things can happen when an individual folder is moved:
If destination does not exist, the folder gets moved. This is the
usual case.
If destination is an existing file, an error occurs.
If destination is a directory, an error occurs.
An error also occurs if a wildcard character that is used in source
doesn't match any folders. The MoveFolder method stops on the first
error it encounters. No attempt is made to roll back any changes made
before the error occurs.
I've marked in bold the parts that explain your problem. Because your destination doesn't end with a trailing backslash, your script is attempting to create the folder, and failing. Try it with a \ added to the end of the destination and report back if it still doesn't work.
Try this:
fso.MoveFolder "C:\Users\michal.glowacki\Desktop\mv_files_backup", "\\192.168.10.245\backup\servers\backup_server\"

Open a file with notepad and save it, using vbscript

My problem is that I want to open a file in notepad and then save it from notepad, not manually but using vbscript (the reason I want this is to overcome some encoding issues). Until now I have found a relevant article which should solve my problem, but it doesn't work. It has this code:
Dim notepad, wndNotepad, strDesktop
Set notepad = Sys.Process("notepad")
Set wndNotepad = notepad.Window("Notepad")
' Open a file in Notepad
wndNotepad.MainMenu.Click("File|Open...")
notepad.Window("#32770", "Open").OpenFile "C:\Program Files\SmartBear\TestComplete 12\install.txt"
' Save the file to the desktop
strDesktop = WshShell.SpecialFolders("Desktop")
wndNotepad.MainMenu.Click "File|Save as..."
notepad.Window("#32770", "Save As").SaveFile strDesktop & "\install.txt"
The problem is that vbscript can't recognize the Sys in the second line (Sys.Process). I assume that in this line a process for notepad should be created (like here) and then something like an object of this process to be returned to the variable notepad (something I don't know if and how can be achived) in order to be used in the third line (notepad.Window("Notepad")).
If anyone has any idea how the code should be in order to work, I would really appreciate the help. Also any other suggestions on how to solve this problem (or any ideas about if it can actually be solved) are very welcome. Thank you for your time.
EDIT
As I said in the comments below, the above code needs the TestComplete software which is expensive. So if anyone has any idea for resolving my issue in another way (other software, other code, other programming language) I would be glad to learn it.
I think you need to copy a file from one path to another. Please refer the below code for copying Files,
Function CopyFile()
strSourceFile = "c:\.....\source.txt"
strDestFile = "c:\.....\dest.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
'Check to see if the file is read-only
If Not fso.GetFile(DestinationFile).Attributes And 1 Then
'The file exists and is not read-only. Safe to replace the file.
fso.CopyFile strSourceFile, strDestFile, strOverWrite
Else
'The file exists and is read-only.
'Remove the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
'Replace the file
fso.CopyFile strSourceFile, strDestFile, strOverWrite
'Reapply the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
End If
End Function

Windows Service That Deletes Contents of C:\Windows\Temp

I have windows service written in vb.net that deletes the contents of a folder (meaning all files, subfolders, and files) in that folder every few minutes.
I need to change the service so that it now deletes the contents of the C:\Windows\Temp folder.
When I edit the path in the service, then recompile, and re-install, the service does not delete the contents of C:\Windows\Temp
I even added code to handle any open/locked files so that the deletion process would just continue, but still nothing.
Sub ClearWinTempDirectory(folder As String)
'Loop over the subdirectories and remove them with their contents
For Each d In Directory.GetDirectories(folder)
Directory.Delete(d, True)
Next
' Finish removing also the files in the root folder
For Each f In Directory.GetFiles(folder)
Try
File.Delete(f)
Catch e As System.IO.IOException
Console.WriteLine(e.Message)
End Try
Next
COBWtl.WriteEntry("All files and folders in the " & folder & " directory that
are not currently locked by applications or processes Have been deleted",
EventLogEntryType.Information, eventID:=9995)
End Sub
I am hoping someone can help me identify why this service does not work when pointed to C:\Windows\Temp but it works without incident when deleting files and folders in C:\MyTestFolder.
My service runs as LocalSystem and SYSTEM has full control on C:\Windows\Temp
I also changed it to run as an administrator account, but that doesn't work either.
I can put the same code into a non-service exe and double click it, and it works and deletes the contents of C:\Windows\Temp -- so I am at a complete loss and hope someone can point me in the right direction on how to figure out what is wrong.
I provided process monitor results, which appear to show the service is accessing C:\windows\temp which is confusing because I put some test files out there that are not open or held up in a process, and those are not being deleted.
Native Process Monitor PML Results File
Process Monitor Extended Results XML File
I was able to fix my own problem. Here is what I found:
The service was successfully accessing C:\Windows\Temp but it was failing due to two exceptions:
1) Permissions Exception where it was denied access to a subfolder or file as a result of permissions
2) IO Problem because the file was open or in use.
In my code, I was only checking for System.IO.Exceptions so when it encountered an Access Failure exception it would break.
Once I discovered this, I modified the exception handling on the catch so that it would check for all exceptions.
Hence the code changed from what it was as listed above to this.
Sub ClearWinTempDirectory(folder As String)
'Loop over the subdirectories and remove them with their contents
For Each d In Directory.GetDirectories(folder)
Try
Directory.Delete(d, True)
Catch e As System.Exception
COBWtl.WriteEntry("The directory " & d & " is
currently locked or is inaccessable and will not be deleted.",
EventLogEntryType.Information, eventID:=9997)
End Try
Next
' Finish the files in the root folder
For Each f In Directory.GetFiles(folder)
Try
File.Delete(f)
Catch e As System.Exception
COBWtl.WriteEntry("The file " & f & " in directory " & folder
& " is currently locked or is inaccessable and will not be
deleted.", EventLogEntryType.Information, eventID:=9997)
End Try
Next
COBWtl.WriteEntry("All files and folders in the " & folder & "
directory that are not currently locked by applications or processes
Have been deleted", EventLogEntryType.Information, eventID:=9995)
End Sub
Problem solved.

Delete file in windows 7 using VB.NET

I have written following code in vb.net to delete the file.
If File.Exists(strPath & "\ReportEng.ini") = True Then
File.SetAttributes(strPath & "\ReportEng.ini", FileAttributes.Normal)
File.Delete(strPath & "\ReportEng.ini")
End If
File.Copy("\\192.168.0.1\SAP_Shared\AddonExtra\ReportEng.ini", strPath & "\ReportEng.ini")
This code works perfectly in windows xp. But in Windows 7,I can not delete it. This OS is hectic OS from developer's point of view. Some or other problem occurs and Microsoft has not considered the developer while building this OS.
How do I delete file in Windows 7 ?
It's so easy to do so;
If My.Computer.FileSystem.FileExists("C:\somefile.ext") Then 'Check whether file exists
My.Computer.FileSystem.DeleteFile("C:\somefile.ext") 'Delete the file!
End If
Have a nice day!
You don't need to delete the file: there is an overload File.Copy Method (String, String, Boolean) which allows overwriting.
You didn't say what error you get. I suspect it is because the user doesn't have write access to the directory. You should probably be using a subdirectory of the directory returned by Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) or maybe .LocalApplicationData, and definitely not the directory containing the program.
Also, using Path.Combine(strPath, "ReportEng.ini") is how you're meant to combine paths - it'll take care of, e.g., the trailing path separator for you.
The preferred method for interfacing with the Windows file system uses the following namespace:
Imports Microsoft.VisualBasic.FileIO.FileSystem
To delete a file:
Dim FileLocation As String = strPath & "\ReportEng.ini"
If Not GetDirectoryInfo(FileLocation).Exists Then
GetFileInfo(FileLocation).Delete()
End If

Client-Side VBScript application, Incorrect Current Working Directory

I'm not understanding this behavior. Maybe someone can explain to me why my current working directory is not what I expect.
On my desktop, I have a folder called STKGui:
C:\Documents and Settings\Lauren\Desktop\STKGui
Located in that directory are the following files: gui.html, style.css, save.html, load.html Within STKGui there are also the following directories: Images, Scripts, and SaveData. Scripts contains various .vbs files, including gui.vbs.
I start with gui.html. I click a button which takes me to load.html. load.html uses scripts from Scripts\gui.vbs. One of the functions loads a database, and to do so I provide the location of the database: C:\Documents and Settings\Lauren\Desktop\STKGui\SaveData\SaveData.accdb Of course I want to use a relative file path instead of a fixed path. My initial attempt to load the database failed; it was trying to load from C:\Documents and Settings\Lauren\Desktop\SaveData\SaveData.accdb. So to troubleshoot I printed out the current working directory; much to my chagrin it was C:\Documents and Settings\Lauren\Desktop
I don't understand why my desktop is my current working directory. Shouldn't it be where the file is running from? I figured it would be either C:\Documents and Settings\Lauren\Desktop\STKGui (the location of load.html) OR C:\Documents and Settings\Lauren\Desktop\STKGui\Scripts (the location of gui.vbs which contains the function that's trying to load the database/printing debug messages of the current working directory).
Can someone explain why the current working directory is what it is, or better yet tell me how to get what I really want, which is the location of the files executing? (I don't care if it's the main STKGui folder or the scripts folder--as long as it's within the application's directory structure I can work with it!)
EDIT (7/14/10 4:02 pm EDT):
Various attempts at printing the current working directory or grabbing files based on what I -thought- was the relative path from my executing script have resulted in my desktop's path instead of the path of the executed script. I stumbled across this link: http://leereid.wordpress.com/2008/03/19/vbscript-current-directory-or-folder/ but none of the solutions are working for me, as I get run-time errors regarding the Wscript object. So while I don't know if any of the solutions on the aforementioned link will produce different results, if someone can help me get at least one of them working so I can find out that may be a step in the right direction.
One of the solutions, reproduced below:
Set oShell = CreateObject("WScript.Shell")
Set ofso = CreateObject("Scripting.FileSystemObject")
oShell.CurrentDirectory = ofso.GetParentFolderName(Wscript.ScriptFullName)
produces the following error:
Object required: 'Wscript' line: 659 char: 1
with line 659 being:
oShell.CurrentDirectory = ofso.GetParentFolderName(Wscript.ScriptFullName)
For Server-Side:
You should be using Server.MapPath() to get your "working directory". For instance, if you want to get the path to your database file in C:\Documents and Settings\Lauren\Desktop\STKGui\SaveData\SaveData.accdb, your app root being C:\Documents and Settings\Lauren\Desktop\STKGui, you would use Server.MapPath("SaveData\SaveData.accdb").
For Client-Side:
Upon closer examination and digging up some memories, I realized that MapPath is only available from the Server class. Instead, you need to create a file system object like this:
''get fs object
Set objFSO = CreateObject("Scripting.FileSystemObject")
''get actual file using path relative to calling vbs file
Set objFile = objFSO.GetFile("SaveData\SaveData.accdb")
''get path to the database
set sPathToDatabase = objFSO.GetAbsolutePathName(objFile)
In case it helps, here is a great resource for working with the file system in vbScript: http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/filesfolders/files/
This solution was NOT ideal, but what I ended up doing was parsing the url in my browser to get the directory.
guiPath = Mid(location.PathName, 2, len(location.PathName))
Set regExp = New RegExp
regExp.IgnoreCase = False
regExp.Global = True
regExp.Pattern = ".*/"
Set matchCollection = regExp.Execute(guiPath)
Set match = matchCollection(0)
guiPath = match.value
regExp.Pattern = "%20"
guiPath = regExp.Replace(guiPath, " ")
systemsDBPath = guiPath & "SaveData\SaveData.accdb"
Like I said, less than ideal. May not even work once I'm working with the application this will be running in. But I couldn't find a better way.

Resources