I'm working on a script that will run as a scheduled task under a local admin account. The heart of the script is as follows:
'Calculate date time
dtm = Now
ymd = (Year(dtm)*10000) + (Month(dtm)*100) + Day(dtm)
hms = (Hour(dtm)*10000) + (Minute(dtm)*100) + Second(dtm)
dString = ymd & "_" & hms
Set Wso = CreateObject("WScript.Shell")
'Write random string to text file for reference by incremental script
Const ForWriting = 2
Set objFile = Fso.OpenTextFile("e:\backups\dString.txt", ForWriting, True)
objFile.WriteLine(dString)
objFile.Close
'Append random string to make full backup name unique'
'Execute full backup creation'
'PROBLEM: Below line will only execute under my domain account
Wso.Run("trueimagecmd /create /filename:""e:\backups\autoBackup_" & dString &"_.tib"" /compression:5 /incremental /partition:""C""")
The above snippet will run fine under my domain account, but will error on the line indicated above with the following:
The system cannot find the file specified
Code: 80070002
Source (null)
This error will not occur when I run it under my account. I'm not familiar enough with the permissions required to run an instance of "Wscript.Shell". Any insight is appreciated.
UPDATE:
trueImagecmd is a command line version of Acronis recovery software. I'm using this script as a way of automating the process for deployment. The command is fine and I can run this script as myself, when running under the local admin account, however, the script executes up to the point indicated, the run command is throwing the error.
UPDATE 2:
Looks like including the full path fixed the problem. Thanks all for your suggestions.
Have you tried calling trueimagecmd with the full path to the executable?
For instance C:\progra~1\trueimage\trueimagecmd.exe
Make sure you have drive E in the other machine from where it generates error. Try using c:\backups\autoBackup_" & dString &".tib" instead of e:\backups\autoBackup" & dString &"_.tib"
Related
I made a simplified version of my code that directly highlights the issue.
I have read dozens of similar issues/solution.
Part of my workflow in VBA in Microsoft Access involves calling an R script that does some logic and returns information to a table in the same database.
It was working until we moved the location of the R installation to a new drive. Changing the path to this new install location does not work. No other code is changed.
cmd = "C:\R\bin\i386\Rscript.exe C:\R\test.R"
Debug.Print cmd
Shell cmd
I get
runtime error '5'
I am using the immediate window to check the paths are correct and copying them into RUN to verify that they do work.
The above outputs:
C:\R\bin\i386\Rscript.exe C:\R\test.R
It works in RUN.
The first thing I found when searching online is to add more (") as shell can handle them weirdly:
cmd = """C:\R\bin\i386\Rscript.exe""" & " " & """C:\R\test.R"""
Or any iterations of using "s in different places, output:
"C:\R\bin\i386\Rscript.exe" "C:\R\test.R"
Same error but works in RUN. I also tried them all successfully in CMD.
It seems just Shell refuses to launch R from that path. I have moved it elsewhere on my C drive with same effect.
I cannot recreate the original R installation path as that shared drive is now completely dead.
EDIT:
I changed to using ShellExecute simply to try and make Notepad ++ open, again works in cmd.
Set objShell = CreateObject("Shell.Application")
objShell.ShellExecute "C:\N\notepad++.exe", "C:\R\test_in.csv", "", "open", 1
This time I hit a "suspicious macro error" that leads me to believe that it may be an antivirus setting (macros are enabled in Access) blocking Shell from calling anything.
After days of testing I have found the solution, hopefully this can help anyone else in a similar situation. Windows Defender only blocks shell calls to non-Microsoft products, so I nested a call to PowerShell within the call to Shell:
Shell ("powershell.exe C:\R\bin\i386\Rscript.exe C:\R\test.R")
Take note you need to play around with the "s a lot ot get it working, my actual pipeline has more arguments and I had to enclose them in 5 sets of "s for it to pass through to powershell properly. IE:
Dim codePath As String: codePath = """""\\example\example"""""
Try these variations using Start or a second Command:
cmd = "Start C:\R\bin\i386\Rscript.exe C:\R\test.R"
or:
cmd = "cmd /c ""C:\R\bin\i386\Rscript.exe C:\R\test.R"""
i have routine for store somes documents into one directory wich run on local drive but get error with network drive if i use path as this "\\172.16.3.145\Directory".
i use this code for create subdirectory needed:
If My.Computer.FileSystem.DirectoryExists(PercorsoDocumenti) = False Then
My.Computer.FileSystem.CreateDirectory(PercorsoDocumenti)
End If
If My.Computer.FileSystem.DirectoryExists(PercorsoOrdini) = False Then
My.Computer.FileSystem.CreateDirectory(PercorsoOrdini)
End If
'+++ creazione della sottodirectory per l'ordine che deve sempre esistere per poter consultare i files presenti +++
If My.Computer.FileSystem.DirectoryExists(PercorsoOrdini & lblIdOrdinePassato.Text) = False Then
My.Computer.FileSystem.CreateDirectory(PercorsoOrdini & lblIdOrdinePassato.Text)
End If
LstViewDocumentiCaricati.Clear()
For Each fileName As String In IO.Directory.GetFiles(PercorsoOrdini & lblIdOrdinePassato.Text)
ImgLstFiles.Images.Add(Icon.ExtractAssociatedIcon(fileName))
LstViewDocumentiCaricati.Items.Add(IO.Path.GetFileName(fileName), ImgLstFiles.Images.Count - 1)
Next
This code work and create directory also in path as "\\server\directory" but get error when i try to list all files in a listview with this other code:
For Each fileName As String In IO.Directory.GetFiles(PercorsoOrdini & lblIdOrdinePassato.Text)
ImgLstFiles.Images.Add(Icon.ExtractAssociatedIcon(fileName))
LstViewDocumentiCaricati.Items.Add(IO.Path.GetFileName(fileName), ImgLstFiles.Images.Count - 1)
Next
The error happen also if i share directory with sufficient permission...it create directory on network drive but go on error when try to list files.
The error are similar to this:
Value of \172.16.3.145\Directory\Docs\document.pdf is not a valid path for filePath
I'm not able to debug in production computer, so i think the error is in listing procedure code because all code firs work (create directory on network drive).
Someone could help me to understand why ?
With code provided in the link How to get the associated icon from a network share file all works perfectly. Tested today with no error or problem. Thanks to all!
Hi I have a perfectly working bat named: start.bat
containing:
start C:\Users\*user*\Documents\*path*\hidebat.vbs
and once it is manually opened it works perfectly, meaning it opens hidebat.vbs, which opens a .bat minimized which uploads files to my cloud. Hence it's verified.
I've added
pause
to the start.bat to see what it does and when I tell excel to open the start.bat it will open cmd and display the exact command as required, but it will not execute the hidebat.vbs.
I expect that there is somehow some path constraint or environment constraint when it is run from excel that prevents it to actually reach out of that limited environment.
Within excel I have tried calling the .bat in 3 different ways with:
Dim path As String
path = Application.ActiveWorkbook.path
path = path & "\"
Dim MY_FILENAME3 As String
MY_FILENAME3 = path & "start.bat"
1.
retVal = Shell(MY_FILENAME3, vbNormalFocus)
' NOTE THE BATCH FILE WILL RUN, BUT THE CODE WILL CONTINUE TO RUN.
If retVal = 0 Then
MsgBox "An Error Occured"
Close #FileNumber
End
End If
2.
PathCrnt = ActiveWorkbook.path
Call Shell(PathCrnt & "start.bat")
3.
Dim batPath As String: batPath = path
Call Shell(Environ$("COMSPEC") & " /c " & batPath & "start.bat", vbNormalFocus)
Does anybody have any clue on why it will not execute the .bat file, or what I could do to ensure it will run correctly?
Note. I think it is because it opens the default path, so I'm gonna tell it to "cd" to the actual path where the excel is saved and where the .bat files are.
Yes that was it, the path was set to some random/standard/working/current path by command, so I had to add:
Print #FileNumber, "cd " & path
to the excel macro
so that start.bat looked like:
cd *path*
start *path*\hidebat.vbs
Hope this helps future me's.
I need to run a few Access macros automatically periodically throughout the day, I do this by scheduling a batch file to open the relevant Access db and run the macro.
The problem that I am having is, if I am working on another Access database and therefore already have an instance of Access open, the batch file runs but only opens the database containing the macro that is supposed to run and stops. So the macro doesn't run.
Has anyone else had this issue or know how to solve it?
The batch files that task scheduler calls look like this:
start /min "C:\Program Files\Microsoft Office 15\root\office15\MSACCESS.EXE" "Q:\TC\DNI_Updater\DNIUPDATER.accdb" /X DailyUpdate
I could not find a way to get the DailyUpdate macro to run in the second Access session when using start /min to open that session.
I'm still unsure whether it's possible, but I gave up and switched to VBScript instead. With that approach, it's easy to start the second Access session minimized and run the macro ...
Option Explicit
Dim AccessExePath, DbPath, CmdLine, objShell
DbPath = "C:\Users\hans\Documents\test_hfu.accdb"
AccessExePath = "C:\Program Files (x86)\Microsoft Office\Office14\MSAccess.exe"
CmdLine = """" & AccessExePath & """ """ & DbPath & """" & " /X DailyUpdate"
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run CmdLine, 7 ' Minimize. The active window remains active.
If this approach is satisfactory, you can use the script file as your scheduled task's "Start a program" Action property ...
I am trying to get the logged in username of the user by using VBS.
I tried some codes which works when I run the script directly (Double Clicking it)
Set wshNetwork = CreateObject("WScript.Network")
strUser = wshNetwork.Username
WScript.Echo "Current User: " & strUser
However, what I need to do is to use CMD to run a scheduled task using the AT command.
When it ran, the username would be the computer's name instead of the logged in user.
This problem also occurs when I run CMD as administrator and use wscript to run the script.
Is there any way to bypass this context and get the logged in user instead of the one that runs the script?
The command
query session console
should provide what you need
For an easier to parse
quser console
EDITED - Included sample vbs code
Dim strCmd
strCmd = "cmd /q /c ""quser console | find /i ""console"" "" "
Dim buffer
buffer = WScript.CreateObject("WScript.Shell").Exec(strCmd).StdOut.ReadAll()
Dim c, consoleUserName
c = InStr(buffer,"console")
If c > 2 Then
consoleUserName = Trim(Mid(buffer,2,c-2))
Else
consoleUserName = ""
End If
WScript.Echo consoleUserName
I suggest you execute the command
set
from the prompt. It may reveal a few items that are set in the environment that may be of interest.
set user
will censor the list so that only variables that start user will be displayed.