Convert A Robocopy Command to VB Script - vbscript

I used to use a line in Robocopy that would allow me to copy all folders in a folder INCLUDING the parent folder, I.E all files/folders in the Blackberry folder INCLUDING the Blackberry folder itself, else without it it would just copy the files within and dump them in the backup location...
The code used was;
for %%a in ("%source%") do SET destination="Backups\%date%\%%~nxa"
Now in VB Script I've got;
sSource = Chr(34) & objFolder.self.Path & Chr(34) & " "
So how would I go about having VB Script (which still calls Robocopy) use the above so that when it backs up it will include the PARENT folder as well?
This was the code I had; Converting Robocopy Batch To VB Script
Thanks in advance!
EDIT: The current content of my script file;
Dim BrowseBackupSource
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(0, "Please browse to the folder you would like to backup.", 1, "C:\")
If objFolder Is Nothing Then
Wscript.Quit
End If
wscript.Echo "folder: " & objFolder.title & " Path: " & objFolder.self.path
Dim BrowseBackupLocation
Set objShell = CreateObject("Shell.Application")
Set objDest = objShell.BrowseForFolder(0, "Please browse to the folder you would like to save the backup to.", 1, "C:\")
If objDest Is Nothing Then
Wscript.Quit
End If
wscript.Echo "folder: " & objDest.title & " Path: " & objDest.self.path
sCmd = "%windir%\System32\Robocopy.exe "
sDate = Day(Now) & "-" & Month(Now) & "-" & Year(Now)
sTime = Hour(Now) & "-" & Minute(Now) & "-" & Second(Now)
sSource = Chr(34) & objFolder.self.Path & Chr(34) & " "
sDestination = Chr(34) & objDest.self.Path & Chr(34) & " "
sSwitches = "/E /Log:"& sTime &".txt"
Set objShell = CreateObject("Wscript.Shell")
objShell.Run(sCmd & sSource & sDestination & sSwitches)

Well, if you need the path to the parent folder to set as root of copy:
dim parentFolderPath
parentFolderPath = WScript.CreateObject("Scripting.FileSystemObject").GetFolder(objFolder.self.Path).ParentFolder.Path
EDIT
You need the name of the selected source directory added to the path of the selected destination so
Set fso = WScript.CreateObject("Scripting.FileSystemObject")
sSourceFolderName = fso.GetFolder(objFolder.self.Path).Name
sDestination = Chr(34) & objDest.self.Path & "\" & sSourceFolderName & Chr(34)
Robocopy will handle the target directory creation

If you want to create a copy of a particular folder for backup, why don't you simply copy that folder to the backup destination and be done with it?
Set fso = CreateObject("Scripting.FileSystemObject")
Set app = CreateObject("Shell.Application")
dst = "C:\backups\" & Year(Now) & "\" & Month(Now) & "\" & Day(Now)
CreatePath dst
Set fldr = app.BrowseForFolder(0, "Example", 1, "c:\Programs")
fso.CopyFolder fldr.Self.Path, dst & "\", True
Sub CreatePath(p)
If Not fso.FolderExists(p) Then
CreatePath fso.GetParentFolderName(p)
fso.CreateFolder p
End If
End Sub

Related

TargetPath is blank - on remote drives

I can't seem to get the WShell to return a value for objShortcut.TargetPath, although it passes the full name fine.
I've been reading that the WShell can have issues with remote disks, and I had been using an external drive.
After testing it on shortcuts on my C: drive with files located on my C: drive, I am finding it still does not work. Instead of echoing the traget path, it echos a blank value.
Edited. Thanks for the tip.
getshorty.vbs
Dim objWSHShell
set objWSHShell = CreateObject("WScript.Shell")
Set wshShell = WScript.CreateObject("WScript.Shell")
strTargetPath=objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))
Set objShortcut = wshShell.CreateShortcut(strTargetPath)
WScript.Echo objShortcut.TargetPath
Set objShortcut = Nothing
Set wshShell = Nothing
This a function to create a shortcut :
Call Shortcut("C:\The Absolute Path of your application goes here","Name of your Shortcut")
'*********************************************************************************
Sub Shortcut(PathApplication,Name)
Dim objShell,DesktopPath,objShortCut,MyTab
Set objShell = CreateObject("WScript.Shell")
MyTab = Split(PathApplication,"\")
If Name = "" Then
Name = MyTab(UBound(MyTab))
End if
DesktopPath = objShell.SpecialFolders("Desktop")
Set objShortCut = objShell.CreateShortcut(DesktopPath & "\" & Name & ".lnk")
objShortCut.TargetPath = Dblquote(PathApplication)
ObjShortCut.IconLocation = "%SystemRoot%\system32\SHELL32.dll,-25"
objShortCut.Save
End Sub
'*********************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'*********************************************************************************
Of course, TargetPath property results to "" (a string of zero length) if the .lnk or .url file does not exist.
The CreateShortcut method returns either a WshShortcut object or a WshURLShortcut object. Simply calling the CreateShortcut method opens an existing shortcut but does not result in the creation of a shortcut.
option explicit
On Error GoTo 0
Dim wshShell, strTargetPath, objShortcut
Set wshShell = WScript.CreateObject("WScript.Shell")
strTargetPath = wshShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))
Set objShortcut = wshShell.CreateShortcut(strTargetPath)
WScript.Echo TypeName(objShortcut) & vbTab & VarType(objShortcut) _
& vbNewLine & "FullName" & vbTab & objShortcut.FullName _
& vbNewLine & "TargetPath" & vbTab & objShortcut.TargetPath
If TypeName(objShortcut) = "IWshShortcut" Then
WScript.Echo "Arguments" & vbTab & objShortcut.Arguments _
& vbNewLine & "Description" & vbTab & objShortcut.Description _
& vbNewLine & "WorkingDir" & vbTab & objShortcut.WorkingDirectory
End If
Output
==>dir /B d:\xxxx\*Shortcut.*
32421790 Shortcut.url
pisma - Shortcut.lnk
==>cscript D:\VB_scripts\SO\32421790.vbs "d:\xxxx\32421790 Shortcut.url"
IWshURLShortcut 8
FullName d:\xxxx\32421790 Shortcut.url
TargetPath http://stackoverflow.com/q/32421790/3439404
==>cscript D:\VB_scripts\SO\32421790.vbs "d:\xxxx\nonexistent Shortcut.url"
IWshURLShortcut 8
FullName d:\xxxx\nonexistent Shortcut.url
TargetPath
==>cscript D:\VB_scripts\SO\32421790.vbs "d:\xxxx\pisma - Shortcut.lnk"
IWshShortcut 8
FullName d:\xxxx\pisma - Shortcut.lnk
TargetPath D:\bat\SU\Files\ruzna pisma.png
Arguments
Description font samples
WorkingDir D:\bat\SU\Files
==>cscript D:\VB_scripts\SO\32421790.vbs "d:\xxxx\nonexistent Shortcut.lnk"
IWshShortcut 8
FullName d:\xxxx\nonexistent Shortcut.lnk
TargetPath
Arguments
Description
WorkingDir
==>

error resume next in vbs

I wan't to upload periodically a file to samba share. My script works perfectly, but it crashes if samba share is not accessible (i.e. server or network is down). It is possible to run my vbs script silently ( to ignore errors ) ?
this is my piece of code:
while True
On Error resume next
NetworkObject.MapNetworkDrive "", ServerShare, False, UserName, Password
Set Directory = FSO.GetFolder(ServerShare)
WScript.Sleep 2000
folderName = "\\10.10.10.10\smb\" & strComputerName
If Not FSO.FolderExists(folderName) Then
FSO.CreateFolder folderName
End If
folderName = "\\10.10.10.10\smb\" & strComputerName & "\" & Year(now)
If Not FSO.FolderExists(folderName) Then
FSO.CreateFolder folderName
End If
folderName = "\\10.10.10.10\smb\" & strComputerName & "\" & Year(now) & "\" & Month(now)
If Not FSO.FolderExists(folderName) Then
FSO.CreateFolder folderName
End If
folderName = "\\10.10.10.10\smb\" & strComputerName & "\" & Year(now) & "\" & Month(now) & "\" & Day(now)
If Not FSO.FolderExists(folderName) Then
FSO.CreateFolder folderName
End If
DestinationFile = folderName & "\" & hour(now) & "_" & minute(now) & "_" &second(now) & ".png"
fso.CopyFile SourceFile & "\1.tmp", DestinationFile
WScript.Sleep 2000
fso.DeleteFile(SourceFile & "\1.tmp")
WScript.Sleep 2000
wend
I tried to use "On Error resume next" statement, but it crashes anyway.
I dont think having an on error resume next statement is the best option, and i believe this is bad coding practice. I would consider doing something like this, which will improve coding and stop repeating code.
NetworkObject.MapNetworkDrive "", ServerShare, False, UserName, Password
Set Directory = FSO.GetFolder(ServerShare)
WScript.Sleep 2000
folderName = "\\10.10.10.10\smb\" & strComputerName
Call Check_Folder(folderName)
folderName = "\\10.10.10.10\smb\" & strComputerName & "\" & Year(now)
Call Check_Folder(folderName)
'add in the rest of the foldernames and call check_folder lines
DestinationFile = folderName & "\" & hour(now) & "_" & minute(now) & "_" &second(now) & ".png"
fso.CopyFile SourceFile & "\1.tmp", DestinationFile
WScript.Sleep 2000
fso.DeleteFile(SourceFile & "\1.tmp")
WScript.Sleep 2000
'Sub to increase code reuse
Sub Check_Folder(folderName)
'Begin error checking
On error resume next
If Not FSO.FolderExists(folderName) Then
FSO.CreateFolder folderName
End If
If err.number <> 0 Then
'There is an error here, do something or nothing
End If
'Clear error
On error go to 0
End Sub

Get a VBS file to scan computer for a file

This is my first post, but I have been programming for a long time now
I just want to ask a quick question and the title explains it all. I want my VBS to run a file, but I dont want it to search just for a specific directory, I want it to just find the file if you know what I mean, because if I gave the script to anyone else, this file could be ANYWHERE on their computer.
This is the current couple of important lines that I am using for running files:
set wshshell = wscript.CreateObject("wscript.shell")
and
wshshell.run <program directory here>
You need a recursive function like this one searching for shortcuts.
Sub GenerateHotkeyInFolder(Fldr)
on error resume next
set WshShell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Set FldrItems=Fldr.Items
For Each oFile in FldrItems
With oFile
If .IsFileSystem = true And .IsLink = true And .Type <> "Shortcut to MS-DOS Program" then
set lnk = WshShell.CreateShortcut(oFile.Path)
If lnk.hotkey <> "" then
Set fsop = fso.GetFile(.Path)
LnkName = "<b>" & fso.GetBaseName(fso.GetFile(.Path)) & "</b><br>" & fsop.ParentFolder.path & "\" & fso.GetBaseName(fso.GetFile(.Path)) & "." & fso.GetExtensionName(fso.GetFile(.Path))
TableVar = TableVar & "<tr><td><b>" & lnk.hotkey & "</b></td><td><a class=TblURL onmouseover='MakeRed()' onmouseout='MakeBlack()' onclick='FindShortcut(" & Chr(34) & lnk.fullname & Chr(34) & ")'>" & lnkname & "</a>" & "</td><td><a class=TblURL onmouseover='MakeRed()' onmouseout='MakeBlack()' onclick='FindShortcut(" & Chr(34) & lnk.targetpath & Chr(34) & ")'>" & lnk.targetpath & "</a></td></tr>" & vbcrlf
End If
ElseIf .IsFileSystem = true And .IsFolder = true then
GenerateHotkeyInFolder(.GetFolder)
End If
End With
Next
End Sub

copy the files with creation date range using VBS (in Sub folder files also)

I tried with this link
copy files between a specified date range
but i am able to copying only root directory
please any one help me
Here you go. Please note that this can potentially create empty directories because it will create a directory and then check to see if each file falls within the specified date range or not. If no files do, the directory will remain empty.
Obviously, you can comment out or delete the WScript.Echo lines. They are for troubleshooting only.
Option Explicit
dim objFSO, strSource, strTarget
set objFSO = CreateObject("Scripting.FileSystemObject")
strSource = "c:\Folder1\"
strTarget = "c:\Copy of Folder1\"
call RecurseCopy(strSource, strTarget, True, #04/15/2012 00:00:01 AM#, #04/16/2012 00:00:01 AM#)
' // Recursively copy all files and folders
Sub RecurseCopy(strSource, strTarget, blnCopySubfolders, dBeginDate, dEndDate)
dim objSource, objTarget
WScript.Echo "Begin RecurseCopy" & vbcrlf & vbcrlf & _
"strSource: " & strSource & vbcrlf & _
"strTarget: " & strTarget
set objSource = objFSO.GetFolder(strSource)
If objFSO.FolderExists(strTarget) = False Then
Wscript.Echo "Now going to create folder: " & strTarget
objFSO.CreateFolder(strTarget)
End If
set objTarget = objFSO.GetFolder(strTarget)
Dim file
for each file in objSource.files
If file.DateCreated => dBeginDate AND file.DateCreated =< dEndDate Then
Wscript.Echo "Copying file: " & file.path & " to " & objTarget.Path
file.Copy objTarget.Path & "\" & file.name
Else
WScript.Echo "File will not be copied because the DateCreated is not within the specified range." & vbcrlf & vbcrlf & _
File.Path & " " & file.DateCreated
End If
next
If blnCopySubfolders = True Then
' ** For each subfolder of current dir, copy files to target and recurse its subdirs
Dim subdir
for each subdir in objSource.subfolders
call RecurseCopy(objSource.Path & "\" & subdir.Name, objTarget.Path & "\" & subdir.Name, True, dBeginDate, dEndDate)
Next
End If
End Sub

copy files between a specified date range

I want to copy files from one folder to another which falls between a specific date range using VBS.
for example i want to copy files from 06/11/2009 to 06/12/2010.
How can I do that in VB script.
Is WMI an option? If so, here's a sample script based on the one from the Hey, Scripting Guy! article How Can I Delete All Files Older Than a Specified Date?:
strComputer = "."
strFolder = "C:\FromFolder"
strNewFolder = "C:\ToFolder"
strDateFrom = "20090611000000.000000+00" ' 06/11/2009
strDateTo = "20100612000000.000000+00" ' 06/12/2010
Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colFiles = oWMI.ExecQuery _
("ASSOCIATORS OF {Win32_Directory.Name='" & strFolder & "'} WHERE " _
& "ResultClass = CIM_DataFile")
For Each oFile in colFiles
If oFile.CreationDate > strDateFrom And oFile.CreationDate < strDateTo Then
'WScript.Echo "Full path: " & oFile.Name
'WScript.Echo "Creation date: " & oFile.CreationDate
oFile.Copy strNewFolder & "\" & oFile.FileName & "." & oFile.Extension
oFile.Delete
End If
Next
Here's a slightly different variant where date checks are included in the WMI query:
strComputer = "."
strDateFrom = "20090611000000.000000+00" ' 06/11/2009
strDateTo = "20100612000000.000000+00" ' 06/12/2010
strNewFolder = "C:\ToFolder"
iFlags = 48
Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colFiles = oWMI.ExecQuery( _
"SELECT * FROM CIM_DataFile" & _
" WHERE Drive = 'C:' AND Path = '\\FromFolder\\'" & _
" AND CreationDate >= '" & strDateFrom & "'" & _
" AND CreationDate <= '" & strDateTo & "'" _
,,iFlags)
For Each oFile in colFiles
'WScript.Echo "Full path: " & oFile.Name
'WScript.Echo "Creation date: " & oFile.CreationDate
oFile.Copy strNewFolder & "\" & oFile.FileName & "." & oFile.Extension
oFile.Delete
Next
A few notes:
The script is non-recursive, that is, it only moves files from the source folder itself and not its subfolders.
Dates are specified in the UTC format. More info about this format is in the article I linked to.
WMI doesn't include methods for moving files and folders, so the script copies then deletes the files.
You can use the FileSystemObject. The following will get the date a file was created:
Dim fso, myfile, d
Set fso = CreateObject("Scripting.FileSystemObject")
Set myfile = fso.GetFile("something.dat")
d = myfile.DateCreated
MsgBox d
Read more here.
Here is an example of how to loop through the files in a given folder. For each file, you can check the date, decide whether you like it, and if so copy the file.

Resources