I´m working with VBScript that ie. displays and saves computer hardware info into txt file. My VBscript do some another stuff too ie. modifies some XML files. Now I want use opensource hardware monitoring software so I can log temps, voltages etc. while i´m running torture tests for the computer. The monitoring software is logging results in CSV format so I have first find out if CSV file exists in source folder because name is always different, and then rename it with computer name (I use inputbox to give that name and you can´t see it in code given below). Anyway I want to copy CSV file to another destination. Problem is that if CSV file is not found in source folder, then that MsgBox pop-ups as many times that there are files in the dest. folder. I know that the problem is in "For Each" loop but don´t know how can I bypass that if CSV file doesn´t exist. I want that MsgBox shows itself only once if CSV file doesn´t exists. Can anybody help me with this one?
dim fso, oshell, strProfilePath, oTFldr, fname, WshShell, txt
Set fso = CreateObject("Scripting.FileSystemObject")
Set oShell = CreateObject("WScript.Shell")
strProfilePath = oShell.ExpandEnvironmentStrings("%USERPROFILE%")
If fso.FolderExists(strProfilePath & "\Desktop\Tests\Software\") then
Set oTFldr = fso.getfolder(strProfilePath & "\Desktop\Tests\Software\")
Else
MsgBox "Software folder doesn´t exists!", vbExclamation + vbOKOnly
End If
For each ofile in oTFldr.Files
If UCase(fso.GetExtensionName(ofile.Name)) = "CSV" then
ofile.name = Compname & ".CSV"
fso.Copyfile strProfilePath & "\Desktop\Tests\Software\" & Compname & ".CSV", "C:\"
exit for
else
MsgBox "Didn´t find any CSV file!", vbExclamation + vbOKOnly
End If
Next
For each ofile in oTFldr.Files
If UCase(fso.GetExtensionName(ofile.Name)) = "CSV" then
ofile.name = Compname & ".CSV"
fso.Copyfile strProfilePath & "\Desktop\Tests\Software\" & Compname & ".CSV", "C:\"
exit for
'else
' MsgBox "Didn´t find any CSV file!", vbExclamation + vbOKOnly
End If
Next
Related
I found (apparently working for everybody) script which only needs to be modified (paths):
Sub NewZip(pathToZipFile)
'WScript.Echo "Newing up a zip file (" & pathToZipFile & ") "
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim file
Set file = fso.CreateTextFile(pathToZipFile)
file.Write Chr(80) & Chr(75) & Chr(5) & Chr(6) & String(18, 0)
file.Close
Set fso = Nothing
Set file = Nothing
WScript.Sleep 500
End Sub
Sub CreateZip(pathToZipFile, dirToZip)
'WScript.Echo "Creating zip (" & pathToZipFile & ") from (" & dirToZip & ")"
Dim fso
Set fso= Wscript.CreateObject("Scripting.FileSystemObject")
pathToZipFile = fso.GetAbsolutePathName(pathToZipFile)
dirToZip = fso.GetAbsolutePathName(dirToZip)
If fso.FileExists(pathToZipFile) Then
'WScript.Echo "That zip file already exists - deleting it."
fso.DeleteFile pathToZipFile
End If
If Not fso.FolderExists(dirToZip) Then
'WScript.Echo "The directory to zip does not exist."
Exit Sub
End If
NewZip pathToZipFile
dim sa
set sa = CreateObject("Shell.Application")
Dim zip
Set zip = sa.NameSpace(pathToZipFile)
'WScript.Echo "opening dir (" & dirToZip & ")"
Dim d
Set d = sa.NameSpace(dirToZip)
' Look at http://msdn.microsoft.com/en-us/library/bb787866(VS.85).aspx
' for more information about the CopyHere function.
zip.CopyHere d.items, 4
Do Until d.Items.Count <= zip.Items.Count
Wscript.Sleep(200)
Loop
End Sub
Can anybody give example how this script should look like with
real paths? I'm trying but it's not working for me.
This script consists solely of two subroutines and thus will never execute anything.
Add the following line to the bottom of the file and it should work (given that the code in the subs is sound, I have not tested):
CreateZip "c:\output\test.zip" "c:\input\"
This will do the following, in order:
Check to see if the output file exists. If it does, it will delete it.
Check to see if the input folder exists, if it does not, the script will exit.
Call the NewZip sub which just creates an "empty" .zip file.
Copy files to the zip file.
Pause for a while, probably to ensure you don't try to access the ZIP before it's done copying.
The contents of the input folder will now be in the zip file in the output folder.
I work in a hospital environment and right now im doing PC deployments. Part of the deployment requires us to view 2 files on a network drive looking for information regarding the old systems. They use specific ports and or TTY's to view information in each department.
I am trying to create a VBS file that can open 2 files in 2 different notepad windows. The first one opens up but the pcview.cfg keeps giving me an error. Im trying to link to the same location that the HBOWEM32 is pointed to. Can anyone solve? For security reasons I have taken out the exact location of the network drive. The code below prompts for a specific folder name which is the old pc name. After entering that data it opens the HBOWEM32 files fine but says it cannot find the other part. I Have manually looked inside the folder and the pcview.cfg file DOES exist. I just want a faster way of opening these rather than brute forcing through the run prompt.
Here is the code.
CONST strDir = "<Netowrk Location)"
Dim WshShell
set objShell = CreateObject("WScript.Shell")
set objFSO = CreateObject("Scripting.FileSystemObject")
function findFolder(strDir, strFlag)
set objFolder = objFSO.GetFolder(strDir)
for each objSubFolder in objFolder.SubFolders
if (inStr(objSubFolder.Name, strFlag)) then
findFolder = objSubFolder.Path
exit function
else
findFolder = findFolder (objSubFolder.Path, strFlag)
end if
next
end function
strFlag = inputBox("Enter Computer Name:")
strWeb = findFolder(strDir, strFlag) & "\HBOWEM32.ini"
objShell.Run strWeb
Set WshShell = CreateObject ("WScript.Shell")
WshShell.Run ("notepad.exe """ + "\\<same location as above>\Pcview.cfg""")
Use Option Explicit
Don't create variables you don't use (WshShell, objShell)
Improve your variable names (strFlag seems to be a computer name, strWeb seems to be the full specification of a file)
Don't lump different info into one variable (strWeb contains the folder path to re-use and the specific file name)
Use diagnostics output (at least while developing)
In code:
Option Explicit
...
Dim strComputer : strComputer = InputBox("Enter Computer Name:")
Dim strFolder : strFolder = findFolder(strDir, strComputer)
Dim strIniFSpec : strIniFSpec = objFSO.BuildPath(strFolder, "HBOWEM32.ini")
WScript.Echo "will run '" & strIniFSpec & "'"
objShell.Run strIniFSpec
Dim WshShell : Set WshShell = CreateObject("WScript.Shell")
Dim strCfgFSpec : strCfgFSpec = objFSO.BuildPath(strFolder, "Pcview.cfg")
Dim strCmd : strCmd = "notepad.exe """ & strCfgFSpec & """"
WScript.Echo "will run '" & strCmd & "'"
WshShell.Run strCmd
(not tested, please be carefull)
I am having a problem with my script not actually producing a zip file. When I test the script with the paths set to something like this:
C:\Users\Bob\Desktop\Folder1\Folder2
with the test log files in folder 1 being deleted if older than 7 days, and being zipped and moved to folder 2, it will run perfectly fine. It will produce the zipped file with all of the log files in it and have the proper naming set.
So I know that at least the logic of the script works for that.
My problem is that I need this script to go through the security logs on a machine and delete any older than 7 days, and then zip up any that are left and be sent to a mounted shared drive. When I change the path to something like:
C:\Windows\System32\Config (where the logs are located)
it will still delete any log files older than 7 days, but it does not produce a zip file with any that are left. It just does nothing even though the script produces no errors. I've been trying to figure this out with no luck going over my code. If anyone could take a look over what I've had and let me know where I've gone astray that would be extremely helpful.
Thank you in advance, the script is found below.
'READ FIRST
'------------------------------------------------------------------------------------------
'Lines 14-53 delete any log files older than 7 days. Changing the value in "iDaysOld =" will change the time frame in which files are kept or deleted.
'If files do not need to be deleted this part of the script can be taken out and the Archive/Move ability will still be intact
'Lines 57-102 contain the ability to Zip your log files and send them to a new folder. The zipped file is named after the localhost and a date/timestamp is appended to the file name.
'------------------------------------------------------------------------------------------
Option Explicit
Dim oFSO, oFolder, sDirectoryPath
Dim oFileCollection, oFile, sDir
Dim iDaysOld
' Specify Directory Path From Where You want to clear the old files
sDirectoryPath = "C:\Windows\System32\config"
' Specify Number of Days Old File to Delete
iDaysOld = 7
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(sDirectoryPath)
Set oFileCollection = oFolder.Files
For each oFile in oFileCollection
'Specify the Extension of file that you want to delete
'and the number with Number of character in the file extension
If LCase(oFSO.GetExtensionName(oFile.Name)) = "log" Then
If oFile.DateLastModified < (Date() - iDaysOld) Then
oFile.Delete(True)
End If
End If
Next
Set oFSO = Nothing
Set oFolder = Nothing
Set oFileCollection = Nothing
Set oFile = Nothing
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")
Dim d : d = Date()
Dim dateStr : dateStr = Year(d) & "-" & Right("00" & Month(d), 2) & "-" & Right("00" & Day(d), 2)
Dim t : t = Time()
Dim timeStr: timeStr = Hour(t) & "-" & Right("00" & Minute(t), 2) & "-" & Right("00" & Second(t), 2)
'Path where logs are located
PathLogs = "C:\Windows\System32\config"
'Loop through the logs and zip
Set objPath = objFSO.GetFolder(PathLogs)
For Each objFile In objPath.Files
If (LCase(objFSO.GetExtensionName(objFile)) = "log") Then
' zip files
Command = """C:\Program Files\7-zip\7z.exe"" a " & PathLogs & "%computername%" & "-" & dateStr & "-" & timeStr & ".zip " & PathLogs & objFile.Name
RetVal = objShell.Run(Command,0,true)
End If
Next
WScript.Echo "Zip Successful."
WScript.Echo "Now Moving Zipped Files into Archived Folder"
'move files
Set objFSO = CreateObject("Scripting.FilesystemObject")
objFSO.MoveFile "C:\Windows\System32\config\*.zip" , "C:\Testscripts\testfolder\Archived"
WScript.Echo "Move Successful."
I'd probably try echoing out the 7zip command line, checking that it looks right and running it manually from the same location as the script runs from. It might look wrong when you see it or 7zip might give you a message to indicate what's going on.
This is my first post so please excuse my ignorance. I am using a vbscript to zip all .csv type files in a particular folder. After some google searches, I have found a workable vbscript to do this and have enabled a scheduled task to automate this.
What I need to do next is to transfer the zip file via sftp and then "move" that zip file into another folder. I believe the former can be achieved using pscp.exe via command line but can someone show me how to do the latter?
Basically the zipping will be done twice a day and so it will have a timestamp similar to yyyymmdd0900.zip (for 9am schedule) and yyyymmdd1800.zip (for 6pm schedule). After the transfer, I want to move (not copy) the zip file generated into another folder.
Any pointers would be greatly appreciated. Thank you all in advance.
EDIT: Here is some code I slapped together based on some Google searches. It does what I want it to do. Please excuse the "pasting" as i couldn't figure out how to format it properly. Currently, it runs the bat file after copying but I just noticed that i need to send (using PuTTY Secure Copy) the "latest" zip file before moving it to the "completed" folder. Can someone please show me how to do this?
Zipping the file and rename the zip file
My Code :
On Error Resume Next
strFilepath = "c:\files"
strDestination = "c:\files\completed\"
strExtension = "csv"
strYear = Year(Now)
strMonth = Right("0" & Month(Now), 2)
strDay = Right("0" & Day(Now), 2)
strHour = Right ("0" & Hour(Now), 2)
strMinute = Right ("0" & Minute (Now), 2)
strZip = strFilepath & "\" & strYear & strMonth & strDay & strHour & strMinute & ".zip"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strFilepath)
For Each objFile in objFolder.Files
strFileExt = objFSO.GetExtensionName(objFile.Path)
If LCase(strFileExt) = LCase(strExtension) Then
ZipFile objFile.Path, strZip
End If
Next
Sub ZipFile(strFileToZip, strArchive)
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FileExists(strArchive) Then
Set objTxt = objFSO.CreateTextFile(strArchive)
objTxt.Write "PK" & Chr(5) & Chr(6) & String(18, Chr(0))
objTxt.Close
End If
Set objApp = CreateObject( "Shell.Application" )
intCount = objApp.NameSpace(strArchive).Items.Count + 1
objApp.NameSpace(strArchive).CopyHere strFileToZip
Do
WScript.Sleep 200
set objNameSpace = objApp.NameSpace(strArchive)
If Not objNameSpace is nothing Then
If objNameSpace.Items.Count = intCount Then
Exit Do
End If
End If
Loop
End Sub
>Move file to a different folder and then run a bat file to secury copy file to a FTP location
'Vars
Dim objFSO, objFileCopy, objFileDelete, dot, files, file
Dim strDestination, folder, subfolder, fileCount, strFilePath
'Strings
strDestination = "C:\Files\Completed\"
strFilePath = "C:\Files"
set objFSO = CreateObject("Scripting.fileSystemObject")
set folder = objFSO.getFolder(strFilePath)
For Each file In folder.files
Set objFileCopy = objFSO.GetFile(file)
If objFSO.GetExtensionName(file) = "zip" Then
objFSO.MoveFile objFileCopy.Path, strDestination
End If
Next
Dim shell
Set shell=createobject("wscript.shell")
Shell.run "C:\testsend.bat"
Set shell=nothing
This will move a file to the specified location.
Sub Move_File(Source_File, Destination_Folder)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.MoveFile Source_File, Destination_Folder
Set fso = Nothing
End Sub
sftp client provides a means to change working directory on the host before performing any file transfers. It would be better to thus transfer the file directly to the target location.
NOTE: The above answer was a result of misunderstanding the question. I read it to mean the file had to be moved on the destination but the real operation was to move the file on the origin.
I found the following example code that moves a file after checking that it exists. Wildcards are allowed for the source parameter but then FileExists may not work. Requires vbscript 2.0 to work.
<%
dim filesys
set filesys=CreateObject("Scripting.FileSystemObject")
If filesys.FileExists("c:\sourcefolder\anyfile.html") Then
filesys.MoveFile "c:\sourcefolder\anyfile.html", "c:\destfolder\"
End If
%>
Is the ZIP compression that is built into Windows XP/Vista/2003/2008 able to be scripted at all? What executable would I have to call from a BAT/CMD file? or is it possible to do it with VBScript?
I realize that this is possible using WinZip, 7-Zip and other external applications, but I'm looking for something that requires no external applications to be installed.
There are VBA methods to zip and unzip using the windows built in compression as well, which should give some insight as to how the system operates. You may be able to build these methods into a scripting language of your choice.
The basic principle is that within windows you can treat a zip file as a directory, and copy into and out of it. So to create a new zip file, you simply make a file with the extension .zip that has the right header for an empty zip file. Then you close it, and tell windows you want to copy files into it as though it were another directory.
Unzipping is easier - just treat it as a directory.
In case the web pages are lost again, here are a few of the relevant code snippets:
ZIP
Sub NewZip(sPath)
'Create empty Zip File
'Changed by keepITcool Dec-12-2005
If Len(Dir(sPath)) > 0 Then Kill sPath
Open sPath For Output As #1
Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
Close #1
End Sub
Function bIsBookOpen(ByRef szBookName As String) As Boolean
' Rob Bovey
On Error Resume Next
bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
End Function
Function Split97(sStr As Variant, sdelim As String) As Variant
'Tom Ogilvy
Split97 = Evaluate("{""" & _
Application.Substitute(sStr, sdelim, """,""") & """}")
End Function
Sub Zip_File_Or_Files()
Dim strDate As String, DefPath As String, sFName As String
Dim oApp As Object, iCtr As Long, I As Integer
Dim FName, vArr, FileNameZip
DefPath = Application.DefaultFilePath
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
strDate = Format(Now, " dd-mmm-yy h-mm-ss")
FileNameZip = DefPath & "MyFilesZip " & strDate & ".zip"
'Browse to the file(s), use the Ctrl key to select more files
FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _
MultiSelect:=True, Title:="Select the files you want to zip")
If IsArray(FName) = False Then
'do nothing
Else
'Create empty Zip File
NewZip (FileNameZip)
Set oApp = CreateObject("Shell.Application")
I = 0
For iCtr = LBound(FName) To UBound(FName)
vArr = Split97(FName(iCtr), "\")
sFName = vArr(UBound(vArr))
If bIsBookOpen(sFName) Then
MsgBox "You can't zip a file that is open!" & vbLf & _
"Please close it and try again: " & FName(iCtr)
Else
'Copy the file to the compressed folder
I = I + 1
oApp.Namespace(FileNameZip).CopyHere FName(iCtr)
'Keep script waiting until Compressing is done
On Error Resume Next
Do Until oApp.Namespace(FileNameZip).items.Count = I
Application.Wait (Now + TimeValue("0:00:01"))
Loop
On Error GoTo 0
End If
Next iCtr
MsgBox "You find the zipfile here: " & FileNameZip
End If
End Sub
UNZIP
Sub Unzip1()
Dim FSO As Object
Dim oApp As Object
Dim Fname As Variant
Dim FileNameFolder As Variant
Dim DefPath As String
Dim strDate As String
Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _
MultiSelect:=False)
If Fname = False Then
'Do nothing
Else
'Root folder for the new folder.
'You can also use DefPath = "C:\Users\Ron\test\"
DefPath = Application.DefaultFilePath
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
'Create the folder name
strDate = Format(Now, " dd-mm-yy h-mm-ss")
FileNameFolder = DefPath & "MyUnzipFolder " & strDate & "\"
'Make the normal folder in DefPath
MkDir FileNameFolder
'Extract the files into the newly created folder
Set oApp = CreateObject("Shell.Application")
oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items
'If you want to extract only one file you can use this:
'oApp.Namespace(FileNameFolder).CopyHere _
'oApp.Namespace(Fname).items.Item("test.txt")
MsgBox "You find the files here: " & FileNameFolder
On Error Resume Next
Set FSO = CreateObject("scripting.filesystemobject")
FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
End If
End Sub
Yes, this can be scripted with VBScript. For example the following code can create a zip from a directory:
Dim fso, winShell, MyTarget, MySource, file
Set fso = CreateObject("Scripting.FileSystemObject")
Set winShell = createObject("shell.application")
MyTarget = Wscript.Arguments.Item(0)
MySource = Wscript.Arguments.Item(1)
Wscript.Echo "Adding " & MySource & " to " & MyTarget
'create a new clean zip archive
Set file = fso.CreateTextFile(MyTarget, True)
file.write("PK" & chr(5) & chr(6) & string(18,chr(0)))
file.close
winShell.NameSpace(MyTarget).CopyHere winShell.NameSpace(MySource).Items
do until winShell.namespace(MyTarget).items.count = winShell.namespace(MySource).items.count
wscript.sleep 1000
loop
Set winShell = Nothing
Set fso = Nothing
You may also find http://www.naterice.com/blog/template_permalink.asp?id=64 helpful as it includes a full Unzip/Zip implementation in VBScript.
If you do a size check every 500 ms rather than a item count it works better for large files. Win 7 writes the file instantly although it's not finished compressing:
set fso=createobject("scripting.filesystemobject")
Set h=fso.getFile(DestZip)
do
wscript.sleep 500
max = h.size
loop while h.size > max
Works great for huge amounts of log files.
Just for clarity: GZip is not an MS-only algorithm as suggested by Guy Starbuck in his comment from August.
The GZipStream in System.IO.Compression uses the Deflate algorithm, just the same as the zlib library, and many other zip tools. That class is fully interoperable with unix utilities like gzip.
The GZipStream class is not scriptable from the commandline or VBScript, to produce ZIP files, so it alone would not be an answer the original poster's request.
The free DotNetZip library does read and produce zip files, and can be scripted from VBScript or Powershell. It also includes command-line tools to produce and read/extract zip files.
Here's some code for VBScript:
dim filename
filename = "C:\temp\ZipFile-created-from-VBScript.zip"
WScript.echo("Instantiating a ZipFile object...")
dim zip
set zip = CreateObject("Ionic.Zip.ZipFile")
WScript.echo("using AES256 encryption...")
zip.Encryption = 3
WScript.echo("setting the password...")
zip.Password = "Very.Secret.Password!"
WScript.echo("adding a selection of files...")
zip.AddSelectedFiles("*.js")
zip.AddSelectedFiles("*.vbs")
WScript.echo("setting the save name...")
zip.Name = filename
WScript.echo("Saving...")
zip.Save()
WScript.echo("Disposing...")
zip.Dispose()
WScript.echo("Done.")
Here's some code for Powershell:
[System.Reflection.Assembly]::LoadFrom("c:\\dinoch\\bin\\Ionic.Zip.dll");
$directoryToZip = "c:\\temp";
$zipfile = new-object Ionic.Zip.ZipFile;
$e= $zipfile.AddEntry("Readme.txt", "This is a zipfile created from within powershell.")
$e= $zipfile.AddDirectory($directoryToZip, "home")
$zipfile.Save("ZipFiles.ps1.out.zip");
In a .bat or .cmd file, you can use the zipit.exe or unzip.exe tools. Eg:
zipit NewZip.zip -s "This is string content for an entry" Readme.txt src
There are both zip and unzip executables (as well as a boat load of other useful applications) in the UnxUtils package available on SourceForge (http://sourceforge.net/projects/unxutils). Copy them to a location in your PATH, such as 'c:\windows', and you will be able to include them in your scripts.
This is not the perfect solution (or the one you asked for) but a decent work-a-round.
to create a compressed archive you can use the utility MAKECAB.EXE
Here'a my attempt to summarize built-in capabilities windows for compression and uncompression - How can I compress (/ zip ) and uncompress (/ unzip ) files and folders with batch file without using any external tools?
with a few given solutions that should work on almost every windows machine.
As regards to the shell.application and WSH I preferred the jscript
as it allows a hybrid batch/jscript file (with .bat extension) that not require temp files.I've put unzip and zip capabilities in one file plus a few more features.