Code must be in VBSCRIPT or Shell Script - shell

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

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

VBScript script as a wrapper for a silent Batch file

I have a batch file that gets some parameters from the command line and returns some values into STDOUT.
I want the batch file to be "silent" (such that the console is not shown), and found out probably the only possibility of using vbs script.
I used this thread for implementing the argument forwarding to the batch file in VBS.
Then, I used the following command for calling the batch file I wrapped:
CreateObject("WScript.Shell").Run batchFilePath & " " & Trim(arglist), 0, False
It turns out that my batch file does run, but its STDOUT is discarded somewhere, and does not make its way back to whom called the VBS script. I.e. the batch file's STDOUT is not redirected into the VBS script's STDOUT.
How can I make the batch file's STDOUT being redirected to the VBS script STDOUT, such that if I start the VBS script from some shell, the batch file's output will be printed to the shell too?
Use Exec instead of Run, like this:
set objShell = CreateObject( "WScript.Shell" )
cmd = "echo Hello World!"
' Run the process
set objRes = objShell.Exec( "cmd /c """ & cmd & """" )
' Wait for the child process to finish
Do While objRes.Status = 0
WScript.Sleep 100
Loop
' Show whatever it printed to its standard output
Wscript.Echo "The output was:" & vbNewLine & objRes.StdOut.ReadAll()
Try this...
Intreturn = WshShell.Run("cmd /c " & path& " " & args & ">c:\batchoutput.txt", 0, true)
Set fso = CreateObject("Scripting.FileSystemObject")
Set objfile = fso.OpenTextFile("c:\batchoutput.txt", 1)
text = objfile.ReadAll
Objfile.Close
Or try this...
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objexc = WshShell.Exec("cmd /c " & command and args) 'replace command and args with proper variables
strOutputText = ""
While Not objexc.StdOut.AtEndOfStream
strOutputText = strOutputText & objexc.StdOut.ReadLine()
Loop
Msgbox strOutputText
You may need some debugging on this.

how do i input a parameter explicitly from outside to the program in vbscript?

i have written a program which calculates the HASH of all files of a folder and saves it an an xml file. now my objective is that i want to give the folder to be evaluated, explicitly from outside the program
Dim WshShell, oExec, input
Set WshShell = CreateObject("WScript.Shell")
Set oExec =_
WshShell.exec("C:\Users\Administrator\Downloads\fciv.exe -md5 -r -xml _
d.xml C:\openssl")
input = ""
Do While oexec.status=0
WScript.Sleep 5000
Loop
this is the program. i tried adding inputbox command thinking i would be able to give the input explicitly. here is the modified program
Dim WshShell, oExec, strin
Set WshShell = CreateObject("WScript.Shell")
strin= inputbox("folder")
Set oExec =_
WshShell.exec("C:\Users\Administrator\Downloads\fciv.exe -md5 -r -xml ex.xml strin")
input = ""
Do While oexec.status=0*
WScript.Sleep 1000
Loop
this is not working :( pls help. what exactly shud i be using thr? also how do i give the same input using a cmd file???
You just need to use the string concatenation operator & to build the command string:
Dim WshShell, oExec, strin
Set WshShell = CreateObject("WScript.Shell")
strin= inputbox("folder")
Set oExec =_
WshShell.exec("C:\Users\Administrator\Downloads\fciv.exe -md5 -r -xml ex.xml """ & strin & """")
input = ""
Do While oexec.status=0
WScript.Sleep 1000
Loop
I took the liberty of adding the appropriate double-quotes in case the input path has spaces. You might want to also add in some validation of the path, eg:
dim fso: set fso = CreateObject("Scripting.FileSystemObject")
if not fso.FolderExists(strin) then
WScript.Echo strin & " not found"
WScript.Quit 1
end if

VB script + automate CLI command by VB script

I write the following VB script in order to run the CLI command - vpnclient.exe
my target is to automate the vpnclcient process and answer “y” when question appears,
I have WIN XP PC
During running the vpnclient.exe in CMD window we get then following question
Do you wish to continue? (y/n):
In my VB I write the “echo y” in order to answer on this question automatically
but question is still stuck in CMD window ,and I cant continue
please advice what chuld be wrong in my code and how to fix it?
MY VB script (vpnclient.exe – exist under VPN directory)
Dim oShell
Set oShell = WScript.CreateObject ("WScript.Shell")
oShell.run "cmd /K CD C:\Program Files\Cisco\VPN & ( echo y | vpnclient.exe connect ""site moon"" )"
Set oShell = Nothing
You can try by creating a file with the commands to be executed on the command line instead of echoing the password.
Here's an example where a text file is created first with the required command and then those commands are invoked from the file.
Public Function FTPDownload(serverName, ftpuser, ftppassword, dirPath, localpath, fileName)
Dim fso, myfile
Set fso = CreateObject("Scripting.FileSystemObject")
'Create FTP.EXE commands file
Set fso = CreateObject("Scripting.FileSystemObject")
Set myfile= fso.OpenTextFile("C:\Regression\Results\ftp_cmd.ini", 2, True)
myfile.WriteLine("open " &serverName )
myfile.WriteLine(ftpuser)
myfile.WriteLine(ftppassword)
myfile.WriteLine("lcd " & localpath )
myfile.WriteLine("cd " & dirPath)
myfile.WriteLine("prompt")
myfile.WriteLine("cr")
myfile.WriteLine("mget *" &fileName &"*" )
myfile.WriteLine("mdelete *" &fileName &"*" )
myfile.WriteLine("close")
myfile.WriteLine("quit")
myfile.Close
'====================The following code executes the FTP script. It creates a Shell object and run FTP program on top of it.===================
Set objShell = CreateObject( "WScript.Shell" )
objShell.Run ("ftp -i -s:" & chr(34) & "C:\Regression\Results\ftp_cmd.ini" & chr(34))
Set objShell = Nothing
End Function

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)

Resources