How to Run a file with a variable name in vbscript - vbscript

I am writing a code that will rename an RDP file downloaded at the Temp folder, and I want the script to run that file too, the new name of the file is a variable, so how can I call both the directory and the file name as variables in a Run command.
I have tried this code but I know something is wrong (dir is the path variable and sNewFile is the file name variable):
CreateObject("WScript.Shell").run "& dir & "\" & sNewFile &"
Update: I edited the line but now it is opening the directory folder but not running the file:
CreateObject("WScript.Shell").run " "&dir&" ""\"" "&sNewFile&" "

Something like:
Dim Fso, WshShell
Set WshShell = CreateObject("WScript.Shell")
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
windirpath=wshShell.ExpandEnvironmentStrings("%SystemDrive%")
ParentFolder = FSO.GetParentFolderName(WScript.ScriptFullName)
sParentFolder = ParentFolder & "\"
TempFolder = windirpath & "\TEMP"
FileName1 = "A.RDP"
FileName2 = "B.RDP"
Fso.MoveFile TempFolder & "\" & FileName1, TempFolder & "\" & FileName2
WshShell.run TempFolder & "\" & FileName2

Instead of trying to run the file from a different directory, I now changed the command to run from the files directory with just the file's name as a variable:
Set shell = CreateObject("WScript.Shell")
shell.CurrentDirectory = dir2
shell.Run sNewFile
Thank you all for the help and suggestions

Related

How do I use 7-zip command line in vb script to delete file from zip folder?

I have this vb script:
Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
set WshShell = WScript.CreateObject("WScript.Shell")
'Run the 7-zip command line instruction via thw WshShell to delete files in Tableau Export Packaged Workbook
desfile = "C:\Tableau_Dashboards\Partner_Life_Cycle\ALL_PARTNERS\twbx\Partner_Life_Cycle_ALL_PARTNERS.zip"
srfile = "C:\Tableau_Dashboards\Partner_Life_Cycle\ALL_PARTNERS\twbx\Data"
strCommand = "C:\Program Files\7-Zip\7z.exe d -tzip & desfile & srfile & "
' Run 7-Zip in shell
WshShell.Run strCommand,0,true
WScript.Sleep 5000
I get the error "Line 15: The system cannot find the file specified"
Line 15 is the WshShell.Run strCommand,0,true part.
How can I fix this?
Thanks
Rick
In your code, the concatenation operator & will be treated as a part of the string since you are not closing the previous string with a quote.
It should be:
strCommand = "C:\Program Files\7-Zip\7z.exe d -tzip" & " " & desfile & " " & srfile
(With space added between the paths.)
As the path to the exe contains space (Program Files), it will have to be enclosed in quotes as: "C:\Program Files\7-Zip\7z.exe"
To get a quote within a string in vbscript, the quote has to be doubled .
strCommand = """C:\Program Files\7-Zip\7z.exe"" d -tzip" & " " & desfile & " " & srfile

Run Rscript.exe with VBScript and spaces in path

I have the followaing run.vbs script
Rexe = "R-Portable\App\R-Portable\bin\Rscript.exe"
Ropts = "--no-save --no-environ --no-init-file --no-restore --no-Rconsole "
RScriptFile = "runShinyApp.R"
Outfile = "ShinyApp.log"
startChrome = "GoogleChromePortable\App\Chrome-bin\chrome.exe --app=http://127.0.0.1:9999"
strCommand = Rexe & " " & Ropts & " " & RScriptFile & " 1> " & Outfile & " 2>&1"
intWindowStyle = 0 ' Hide the window and activate another window.'
bWaitOnReturn = False ' continue running script after launching R '
' the following is a Sub call, so no parentheses around arguments'
CreateObject("Wscript.Shell").Run strCommand, intWindowStyle, bWaitOnReturn
WScript.Sleep 1000
CreateObject("Wscript.Shell").Run startChrome, intWindowStyle, bWaitOnReturn
It works pretty well in most cases except when the user puts the run.vbs script in a folder with spaces in its name: e.g. if run.vbs is in folder "foo bar", the user gets the error : "C:\Users\[user name]\Desktop\foo" not recognized as internal command...
I don't understand why Rscript.exe looks for the absolute path before running even if it's called from its parent directory using relative path.
I heard about the double quote solution using the absolute path but it doesn't seem to work with .exe scripts (it does though with .bat and .cmd)
Thanks for any help!
Below code will help you
Dim oShell As Object
Set oShell = CreateObject("WScript.Shell")
'run command'
Dim oExec As Object
Dim oOutput As Object
Set oExec = oShell.Exec("C:\Program Files\R\R-3.2.3\bin\Rscript.exe C:\subfolder\YourScript.R " & """" & var1 & """")
Set oOutput = oExec.StdOut
handle the results as they are written to and read from the StdOut object
Dim s As String
Dim sLine As String
While Not oOutput.AtEndOfStream
sLine = oOutput.ReadLine
If sLine <> "" Then s = s & sLine & vbCrLf
Wend

VBS Script, CopyFile File

I am new to vbs scripting, I have been working on a script to create a directory with user input. Then the script copies a specific file into the newly created directory. I can't seem to get the file into the newly created directory. any help would be great!!
dim UserName
Do
UserName = InputBox ("Enter Client Name with no spaces IE: lastname_firstname")
If UserName = "" then
Msgbox "No Username entered"
end if
Loop Until UserName <> ""
MsgBox "Please click OK to continue"
MsgBox "Check \\server\path\share\ for NEW client folder"
Set objShell = CreateObject("Wscript.Shell")
objShell.Run "cmd /c mkdir \\server\path\share\" & UserName
sPath = "\\server\path\share\"
Set oShell = CreateObject("WScript.Shell")
oShell.Run "explorer /n," & sPath & UserName, 1, False
Set oShell = Nothing
dim filesys
set filesys=CreateObject("Scripting.FileSystemObject")
If filesys.FileExists("\\server\path\share\some_type_file.docx") Then
filesys.CopyFile "\\server\path\share\some_type_file.docx", "\\server\path\share\" <<COPY FILE INTO NEWLY CREATED DIRECTORY "UserName">>
End If
Try to change the last line to this
filesys.CopyFile "\\server\path\share\some_type_file.docx", "\\server\path\share\" & UserName & "\"

Trouble compressing large files using vbs

I have jumbled up a vbs script to compress files older than 7 days using 7za's command line utility. While most of the logic works fine, I am able to compress single file into single zip file.
The problem arises when I try to add all matching files to one zip file. Below is the code snippet:
strCommand = "7za.exe -mx=9 a " & ObjectFolder & sysDate & ".zip " & strFileName
strRun = objShell.Run(strCommand, 0, True)
Now as per the 2nd line, setting True would make sure the script will wait till command is finished executing. But the problem is 7za is exiting immediately and going to the next loop, processing the next file and since it tries to create same zip file, I get access denied error.
Can someone please help me to fix this?
I have also tested the scenario in command prompt. What I did was, execute below 2 commands simultaneously in separate prompts:
Prompt 1:
C:\7za.exe -mx=9 a test.zip c:\sample1.pdf
Prompt 2:
C:\7za.exe -mx=9 a test.zip c:\sample2.pdf
Prompt 2 resulted in following error:
Error: test.zip is not supported archive
System error:
The process cannot access the file because it is being used by another process.
This is the same error I am getting in my script and I need help in resolving this. Any pointers will be helpful!
UPDATE:
With the great pointers provided by both John and Ansgar, I was able to resolve this! It turned out to be a bug in my script! In my script, I included a check to see if the file is in use by any other process before processing it for archive. So I was checking this by opening the file for appending using:
Set f = objFSO.OpenTextFile(strFile, ForAppending, True)
But before proceeding to process the same file, I was not CLOSING it in the script, hence the error: The process cannot access the file because it is being used by another process
After I closed the file, all went well!
Thanks Again for all the great support I got here!
As a token of gratitude, I am sharing the whole script for anyone's use. Please note that I am not the original author of this, I gathered it from various sources and tweaked it a little bit to suit my needs.
Archive.vbs
Const ForAppending = 8 ' Constant for file lock check
Dim objFSO, objFolder, objFiles, objShell
Dim file, fileExt, fileName, strCommand, strRun, strFile
Dim SFolder, OFolder, Extension, DaysOld, sDate
'''' SET THESE VARIABLES! ''''
SFolder = "C:\SourceFolder\" 'Folder to look in
OFolder = "C:\OutputFolder\" 'Folder to put archives in
Extension = "pdf" 'Extension of files you want to zip
DaysOld = 1 'Zip files older than this many days
''''''''''''''''''''''''''''''
sDate = DatePart("yyyy",Date) & "-" & Right("0" & DatePart("m",Date), 2) & "-" & Right("0" & DatePart("d",Date), 2)
'Create object for playing with files
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Create shell object for running commands
Set objShell = wscript.createObject("wscript.shell")
'Set folder to look in
Set objFolder = objFSO.GetFolder(SFolder)
'Get files in folder
Set objFiles = objFolder.Files
'Loop through the files
For Each file in objFiles
fileName = Split(file.Name, ".")
fileExt = fileName(UBound(fileName))
'See if it is the type of file we are looking for
If fileExt = Extension Then
'See if the file is older than the days chosen above
If DateDiff("d", file.DateLastModified, Now()) >= DaysOld Then
strFile = file.Path
'See if the file is available or in use
Set f = objFSO.OpenTextFile(strFile, ForAppending, True)
If Err.Number = 70 Then ' i.e. if file is locked
Else
f.close
strFName = objFSO.GetBaseName(file.name)
strCommand = "C:\7za.exe -mx=9 a " & OFolder & sDate & ".zip " & strFile
strRun = objShell.Run(strCommand, 0, True)
'wscript.echo strCommand ' un-comment this to check the file(s) being processed
'file.Delete ' un-comment this to delete the files after compressing.
End If
End If
End If
Next
'Cleanup
Set objFiles = Nothing
Set objFolder = Nothing
Set objFSO = Nothing
Set objShell = Nothing
wscript.Quit
===========================
Thanks
-Noman A.
Not quite what you asked for, but here's a batch script I use for a similar task in case that helps get you past of your immediate issue:
ArchiveScriptLog.Bat
::ensure we're in the right directory, then run the script & log the output
cls
pushd "c:\backup scripts"
ArchiveScript.bat > ArchiveScript.log
popd
ArchiveScript.bat
::Paths (must include the \ on the end). There must be no space between the equals and the value
::UNC paths are acceptable
Set FolderToBackup=F:\EnterpriseArchitect\Energy\
Set BackupPath=F:\EnterpriseArchitect\!ARCHIVE\
Set RemoteBackupPath=\\ukccojdep01wok\h$\Energy\cciobis01edc\
Set SevenZip=C:\Program Files (x86)\7-Zip\
::Get DATE in yyyymmdd format; done in two lines to make it easy to change the date format
FOR /F "TOKENS=2,3,4 DELIMS=/ " %%A IN ('echo %Date%') DO (SET mm=%%A&SET dd=%%B&SET yyyy=%%C)
SET strDate=%yyyy%%mm%%dd%
::Set the Backup File to be the backup path with the current date & .zip on the end
Set BackupFile=%BackupPath%%strDate%.zip
::create a zip containing the contents of folderToBackup
pushd %SevenZip%
7z a "%BackupFile%" "%FolderToBackup%"
popd
::go to the archive directory & copy all files in there to the remote location (this accounts for previous errors if the network were unavailable)
pushd "%BackupPath%"
move *.zip "%RemoteBackupPath%"
popd
::delete off backups in the remote location which are older than 90 days
pushd "%RemoteBackupPath%"
forfiles /D -90 /M *.zip /C "cmd /c del #file"
popd
Your command shouldn't return before 7za has finished its task (and it doesn't in my tests). Try changing your code to the following, so you can see what's going on:
strCommand = "7za.exe -mx=9 a " & ObjectFolder & sysDate & ".zip " & strFileName
strCommand = "%COMSPEC% /k " & strCommand
strRun = objShell.Run(strCommand, 1, True)
It may also be a good idea to quote the filenames:
Function qq(str)
qq = Chr(34) & str & Chr(34)
End Function
strCommand = "7za.exe -mx=9 a " & qq(ObjectFolder & sysDate & ".zip") & " " _
& qq(strFileName)

VBscript to zip log files with 7zip

Would like someone to take a look at my script and tell me where I am messing up.
It is a script to zip log files and then I would like to move them into a new folder that is going to be shared over a network. Right now I am just trying to get the part where it zips up the files using 7zip correctly.
I am very new to VB (like 2 days) so having some syntax problems I think.
Script is found below, thank you in advance for all advice and help
Option Explicit
WScript.Echo "Press to start zipping log files."
Dim objFile, objPath, objFolder, Command, PathLogs, RetVal
Dim objFSO: Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objShell: Set objShell = CreateObject("WScript.Shell")
PathLogs = "C:\Testscripts\testfolder\" 'This path just has some test logs
' Loop through the logs and zip and move each file (if required, you could just move files with an '.log' extension)
Set objPath = objFSO.GetFolder(PathLogs)
For Each objFile In objPath.Files
If (LCase(objfso.GetExtensionName(objFile)) = "log") Then
Wscript.Echo objFile.Name
' zip and move files
'Command = """C:\Program Files\7-zip\7z.exe"" -m -ex """ & PathLogs & \objFile.Name objfso.GetBaseName(objFile) & "*.zip"" """ & PathLogs & objFile.Name & """"
Command = ""C:\Program Files\7-zip\7z.exe"" a -m -ex " & PathLogs & "" & objFile.Name & ".zip " & PathLogs & "" & objFile.Name & "
WScript.Echo "Command: " & Command
RetVal = objShell.Run(Command,0,true)
End If
Next
WScript.Echo "Zip Successful."
You have your quotes wrong. To use a quote inside a string, you have to duplicate the quote.
Command = """C:\Program Files\7-zip\7z.exe"" a -m -ex " _ 'this is the first part of the string
& PathLogs & objFile.Name & ".zip " & PathLogs & objFile.Name
If your Logfile or PathLogs can contain spaces they must be quoted as well.

Resources