How to rename an existing file in VB Script? [duplicate] - vbscript

This question already has answers here:
Rename files without copying in same folder
(2 answers)
Closed 5 years ago.
I am very new to VB Script. I am trying to rename a file through VB Script could any one please help me in this ?
I just tried this but didn't work.
Dim OldFile As String
Dim NewFile As String
OldFile = "C:\apache-tomcat-8.0.44\apache-tomcat-8.0.44\webapps\" & "\" & timeStampDir & "\" & "output_11.docx"
NewFile = "C:\apache-tomcat-8.0.44\apache-tomcat-8.0.44\webapps\" & "\" & timeStampDir & "\" & "output.docx"
Name OldFile As NewFile

Use FileSystemObject and use Name property of a object referring the file you want to rename.
Dim OldFile, FSO, objFile
Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
OldFile = "C:\apache-tomcat-8.0.44\apache-tomcat-8.0.44\webapps\" + CStr(timeStampDir) + "\output_11.docx"
Set objFile = FSO.GetFile(OldFile)
objFile.Name = "output.docx"
Keep in mind that you need to correctly escape all of the whitespaces in your oldFile variable, otherwise the file may not be found.

Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.MoveFile OldFile, NewFile
Set objFSo = Nothing

Related

How to Run a file with a variable name in 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

Code must be in VBSCRIPT or Shell Script

Hi I need to read from a text file and copy files whose name are present in that file. location of the files are different and i need to copy it from one location to another
Const DestinationFile = "C:\Users\$svijay8\Desktop\libnew\"
Const SourceFile = "C:\Users\$svijay8\Desktop\lib\*"
Dim fso
Dim fName
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(DestinationFile) Then
WScript.Echo "Folder is there"
Else
Set fso = CreateObject("Scripting.FileSystemObject")
Set listFile = fso.OpenTextFile("inputold.txt")
do while not listFile.AtEndOfStream
fName = listFile.ReadLine()
Set fName = fso.GetFile(C:\Users\$svijay8\Desktop\lib\*so)
If fname.FileExists("C:\Users\$svijay8\Desktop\lib\*") Then
WScript.Echo "Reached If loop in do while in If condition above copy"
fso.CopyFile SourceFile, "C:\Users\$svijay8\Desktop\libnew\", True
Else
End If
loop
End If
Not sure what you mean by "Code must be in VBScript or ??shell??". Do you mean Powershell? or MS-DOS BATCH commands for CMD.EXE? Or have you installed a proper Unix-like shell (e.g. bash) on your Windows box?
Anyway, you should be able to do it like this - if you call this "shell".
For /f %%f in (inputold.txt) do copy /y c:\source\%%f c:\dest

.vbs script gets stuck when run as Scheduled Task

I have a VBS file that was provided to me, and I have made small changes to. The script runs fine when I double click it, however when it's set to run as a scheduled task, the status remains as "Running"; usually the task is completed in a matter of seconds.
Can anyone suggest why this may be?
Thanks
wscript.echo "VBScript Create_TaxiCheck_File"
Const InputFile = "C:\TaxiCheckLive\TaxiCheck_Data.txt"
Const OutputFile = "C:\TaxiCheckLive\TaxiCheck_Formatted.txt"
Const CSVFile = "C:\TaxiCheckLive\ChelmsfordExtract.csv"
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Dim fso
Dim I
Dim IF1
Dim OF1
Dim InputLine
Dim Outputline
Dim comma
Set fso = CreateObject("Scripting.FileSystemObject")
'check input file exists
if (fso.fileexists(InputFile)) then
wscript.echo "Input file exists: " & InputFile
'Write to log file (File exists)
Set LogFile = fso.OpenTextFile("LogFile.txt", ForAppending)
LogFile.WriteLine DateInfo & Now & " - OK, Input file exists"
LogFile.close
Else
'Write to log file (File does not exist)
Set LogFile = fso.OpenTextFile("LogFile.txt", ForAppending)
LogFile.WriteLine DateInfo & Now & " - Error, input file does not exist, database export has not run!" & VbCrLf
LogFile.close
wscript.Quit(9)
end if
'if exists then delete output file
if (fso.fileexists(OutputFile)) then
wscript.echo "Deleting file: " & OutputFile
Set OF1 = fso.GetFile(OutputFile)
OF1.Delete
end if
'create output file
wscript.echo "Creating output file: " & OutputFile
Set OF1 = fso.CreateTextFile(OutputFile, True)
OF1.Close
'if exists then delete CSV file
if (fso.fileexists(CSVFile)) then
wscript.echo "Deleting file: " & CSVFile
Set OF1 = fso.GetFile(CSVFile)
OF1.Delete
end if
'create formated output file.
wscript.echo "Create formated output file."
Set IF1 = fso.OpenTextFile(InputFile, ForReading)
Set OF1 = fso.OpenTextFile(OutputFile, ForWriting)
Outputline = "MODE,VEH_REG_NO_NO_SPACES,VEH_MAKE,VEH_MODEL,VEH_COLOUR,LIC_NUMBER"
OF1.WriteLine Outputline
Outputline = "D,*"
OF1.WriteLine Outputline
Outputline = ""
Do While Not IF1.AtEndOfStream
InputLine = IF1.ReadLine
Outputline = "I," + InputLine
OF1.WriteLine Outputline
Outputline = ""
Loop
'copy output file to CSV file
fso.CopyFile OutputFile, CSVFile
'close input and output files
IF1.Close
OF1.Close
'delete input and output files
Set OF2 = fso.GetFile(InputFile)
OF2.Delete
Set OF3 = fso.GetFile(OutputFile)
OF3.Delete
'ftp file to firmstep ftp site
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run("%windir%\system32\ftp.exe -s:C:\TaxiCheckLive\ftpcommands.txt")
wscript.echo "VBScript Create_TaxiCheck_File Ended Successfully"
'Write to log file (complete)
Set LogFile = fso.OpenTextFile("LogFile.txt", ForAppending)
LogFile.WriteLine DateInfo & Now & " - Script completed running" & VbCrLf
LogFile.close
wscript.Quit(1)
wscript.echo in an unattended VBS can cause issues, as the script will be waiting for someone to hit the 'ok' button. Remove them or comment them out.
I had a similar problem.
My scheduled task was running under a specific user. Using the component services snap in for MMC I needed to give the user 'Launch and activation' permissions. Once this was done, the scheduled task ran correctly.
The line 'CreateObject("Scripting.FileSystemObject")' will require these permissions I believe.

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