How can I pass the argument in vbs - windows

I'm a linux guy and new to windows, im trying to create a small vbs script to create bunch of folders.
Im trying to create a mainfolder according to user input and 4 subfolder in it with static names. I somehow got two seperate working scripts for mainfolder and subfolder but I would like to combine them both which means once the mainfolder is created as per user input next it should create subfolders below that.
Script which creates Mainfolder.vbs as per user input:
strfolder = InputBox("Please enter a name for your new folder:")
set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.CreateFolder "C:\test\" & strfolder
Script which creates subfolders.vbs folders:
Option Explicit
dim wshShell
set wshShell = wscript.CreateObject("WScript.Shell")
DIM fSO
DIM foldername1
DIM foldername2
DIM foldername3
DIM foldername4
foldername1=("subfolder1")
foldername2=("subfolder2")
foldername3=("subfolder3")
foldername4=("subfolder4")
dim folderpath
SET FSO=CreateObject("Scripting.FileSystemObject")
folderpath = "C:\test" & _
"\" & foldername1
wscript.echo "Creating folder: " & folderpath
FSO.CREATEFOLDER(folderpath)
folderpath = "C:\test" & _
"\" & foldername2
wscript.echo "Creating folder: " & folderpath
FSO.CREATEFOLDER(folderpath)
folderpath = "C:\test" & _
"\" & foldername3
wscript.echo "Creating folder: " & folderpath
FSO.CREATEFOLDER(folderpath)
folderpath = "C:\test" & _
"\" & foldername4
wscript.echo "Creating folder: " & folderpath
FSO.CREATEFOLDER(folderpath)
In short, how can I create a mainfolder as per user input and subfolders with static names?
would like to combine these both and work together as a single script.

You can try with this subroutine : SmartCreateFolder(strFolder)
Sub SmartCreateFolder(strFolder)
With CreateObject("Scripting.FileSystemObject")
If Not .FolderExists(strFolder) then
SmartCreateFolder(.getparentfoldername(strFolder))
.CreateFolder(strFolder)
End If
End With
End Sub
The combined whole script can be written like that :
Option Explicit
Const Title = "SmartCreateFolder"
Const Time2Wait = 2
Dim ws,MainFolderPath,MainFolderName,SubFolderPath,Arr_SubFolder_Name,i
Set ws = CreateObject("wscript.shell")
Arr_SubFolder_Name = Array("subfolder1","subfolder2","subfolder3","subfolder4")
MainfolderName = InputBox(_
"Please enter a name for your new folder :",Title,"Type the name here")
If MainfolderName = "" Then Wscript.Quit(1)
MainFolderPath = "C:\test\" & MainfolderName
For i=LBound(Arr_SubFolder_Name) To UBound(Arr_SubFolder_Name)
Call SmartCreateFolder(MainFolderPath)
SubFolderPath = MainFolderPath & "\" & Arr_SubFolder_Name(i)
Call SmartCreateFolder(SubFolderPath)
Next
ws.run "Explorer " & MainFolderPath
'---------------------------------------------------------------
Sub SmartCreateFolder(strFolder)
With CreateObject("Scripting.FileSystemObject")
If Not .FolderExists(strFolder) then
ws.Popup "Creating folder: " & StrFolder,Time2Wait,_
Title,vbInformation+vbSystemModal
SmartCreateFolder(.getparentfoldername(strFolder))
.CreateFolder(strFolder)
End If
End With
End Sub
'---------------------------------------------------------------

Related

VB Script referencing a Variable which is defined from a macro

I need some help with this VB script (edit: it is being used in QlikView)- it is copying a file to a different location (checks if the file already exists in the destination folder).
It works when the source filename and location is hardcoded but this is going to be a variable which is defined in a different macro.
So the source filename and location will be defined by varFileOpen.
Basically in the code, instead of:
SourceFile = "C:\file_path\file_name.txt"
to be like this:
SourceFile = varFileOpen
where varFileOpen has been defined from a different SUB (it is the full file path).... I can't get it to work?
Sub that creates the varFileOpen:
'Sub to get open file dialog
SUB ShowOpen
OpenSave "varFileOpen", 0, "Text file (*.txt)|*.txt|All files (*.*)|*.*", "h:\", "Select a file to open"
END SUB
' Sub to show browse folder dialog
SUB Folder (objVariable)
ON ERROR RESUME NEXT
SET objShell = CREATEOBJECT("Shell.Application")
SET objFolder = objShell.BrowseForFolder (WINDOW_HANDLE, TITLE, OPTIONS, ROOT)
SET objFolderItem = objFolder.Self
strPathAndFile = objFolderItem.Path
SET objSavePath = ActiveDocument.Variables(objVariable)
objSavePath.SetContent strPathAndFile, TRUE
ON ERROR GOTO 0
END SUB
' Sub to show open/save dialog
SUB OpenSave (objVariable, intType, strFilter, strInitialDirectory, strDialogText)
' Create objects
SET objShell = CREATEOBJECT("WScript.Shell")
SET objFSO = CREATEOBJECT("Scripting.FileSystemObject")
strTempDir = objShell.ExpandEnvironmentStrings("%TEMP%")
strTempFile = strTempDir & "\" & objFSO.GetTempName
' Temporary powershell script file to be invoked
strPSFile = tempFile & ".ps1"
' Temporary file to store standard output from command
strPSOutFile = tempFile & ".txt"
' Create script to run
strPSScript = strPSScript & "[System.Reflection.Assembly]::LoadWithPartialName(""System.windows.forms"") | Out-Null" & vbCRLF
' Check type (Open (0) or Save (1))
IF intType = 1 THEN
strPSScript = strPSScript & "$dlg = New-Object System.Windows.Forms.SaveFileDialog" & vbCRLF
ELSE
strPSScript = strPSScript & "$dlg = New-Object System.Windows.Forms.OpenFileDialog" & vbCRLF
END IF
' Set initial directory
strPSScript = strPSScript & "$dlg.initialDirectory = " & CHR(34) & strInitialDirectory & CHR(34) & vbCRLF
' Set file filter/s
strPSScript = strPSScript & "$dlg.filter = " & CHR(34) & strFilter & CHR(34) & vbCRLF
strPSScript = strPSScript & "$dlg.FilterIndex = 1" & vbCRLF
' Set dialog text
strPSScript = strPSScript & "$dlg.Title = " & CHR(34) & strDialogText & CHR(34) & vbCRLF
' Show help (seems it must be set to true)
strPSScript = strPSScript & "$dlg.ShowHelp = $True" & vbCRLF
' Show the dialog
strPSScript = strPSScript & "$dlg.ShowDialog() | Out-Null" & vbCRLF
strPSScript = strPSScript & "Set-Content """ &strPSOutFile & """ $dlg.FileName" & vbCRLF
' Write result
SET objResultFile = objFSO.CreateTextFile(strPSFile, TRUE)
objResultFile.WriteLine(strPSScript)
objResultFile.Close
SET objResultFile = NOTHING
' Run command in PowerShell
strPSCMD = "powershell -ExecutionPolicy unrestricted &'" & strPSFile & "'"
objShell.Run strPSCMD, 0, TRUE
' Open result file and read result
SET objResultFile = objFSO.OpenTextFile(strPSOutFile, 1, 0, -2)
strPathAndFile = objResultFile.ReadLine
objResultFile.Close
SET objResultFile = NOTHING
' Add to result to variable
SET objSavePath = ActiveDocument.Variables(objVariable)
objSavePath.SetContent strPathAndFile, TRUE
' Delete temp-files
objFSO.DeleteFile(strPSFile)
objFSO.DeleteFile(strPSOutFile)
END SUB
The above code opens explorer & you are able to select a file and the path is copied - varFileOpen.
The following SUB moves the file:
SUB movefile
Const DestinationFile = "c:\destfolder\anyfile.txt"
Const SourceFile = "C:\file_path\file_name.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
'Check to see if the file already exists in the destination folder
If fso.FileExists(DestinationFile) Then
'Check to see if the file is read-only
If Not fso.GetFile(DestinationFile).Attributes And 1 Then
'The file exists and is not read-only. Safe to replace the file.
fso.CopyFile SourceFile, "C:\destfolder\", True
Else
'The file exists and is read-only.
'Remove the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
'Replace the file
fso.CopyFile SourceFile, "C:\destfolder\", True
'Reapply the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
End If
Else
'The file does not exist in the destination folder. Safe to copy file to this folder.
fso.CopyFile SourceFile, "C:\destfolder\", True
End If
Set fso = Nothing
END SUB
You will need to pass the value into the Sub for it to have scope, which means you will need to define the sub like this so that it accepts a parameter
Public Sub MySub(byVal SourceFile)
ByVal just means you pass the Value of the variable rather than the actual variable itself.
And you would call it from the other sub with
MySub varFileOpen
EDIT: Based on the code displayed above, you would need to change Sub movefile to Sub movefile(byVal SourceFile) and remove the Const delaration of SourceFile. Once that was done, all you would have to do is change whatever is calling movefile (I can't see anything in the code you've posted doing this?) to call it with movefile varToOpen instead
Try my CustomFileDialog.
Usage:
Dim fDialog
Set fDialog = New CustomFileDialog
fDialog.FilterString = "Text Files (*.txt)|*.txt"
fDialog.InitialDirectory = "C:\"
fDialog.DialogText = "Select a file to open"
fDialog.Show
fDialog.MoveFile "C:\stackoverflow\temp\New File Name.TXT"
CustomFileDialog
Class CustomFileDialog
Public SourceFile
Public FilterString
Public InitialDirectory
Public DialogText
Public Sub Show
Set toolkit = CreateObject("Vbsedit.toolkit")
Files = toolkit.OpenFileDialog(InitialDirectory, FilterString, False, DialogText)
If UBound(Files) >= 0 Then
SourceFile = Files(0)
Else
SourceFile = ""
End If
End Sub
Public Sub MoveFile(DestinationFile)
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(DestinationFile) Then fso.DeleteFile DestinationFile, True
fso.CopyFile SourceFile, DestinationFile, True
End Sub
End Class

vbscript to create multiple hidden subfolders

I have a script that creates a subfolder named 'pst' to all folders in the root directory c:\test. What code do I need to add to this script to make the 'pst' folder hidden?
folder_path = "c:\test"
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(folder_path)
For each f in folder.SubFolders
fso.CreateFolder(f & "\PST")
next
Any help is greatly appreciated.
All you need to do is play with the folder attributes.
Const Directory = 16
Const Hidden = 2
folder_path = "c:\test"
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(folder_path)
For each f in folder.SubFolders
With fso.CreateFolder(fso.BuildPath(f, "PST")) 'returns folder object
.Attributes = Directory Or Hidden 'set hidden flag for directory
End With
Next
You can try something like this :
Option Explicit
Dim fso,folder_path,folder,f
folder_path = "c:\test"
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(folder_path)
For each f in folder.SubFolders
'wscript.echo f & "\PST"
If Not fso.FolderExists(f & "\PST") Then
fso.CreateFolder(f & "\PST")
Call Hide(f & "\PST")
End If
If fso.FolderExists(f & "\PST") Then
Call Hide(f & "\PST")
End If
Next
'**********************************************
Sub Hide(MyFolder)
Dim Command,Result,Ws
Command = "Cmd /c attrib +h " & DblQuote(MyFolder) &""
'wscript.echo Command
Set Ws = CreateObject("Wscript.Shell")
Result = Ws.Run(Command,0,True)
End Sub
'**********************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************

Copy all .xlsx files from source folder and rename it by appending "_Report"

I want to copy all .xlsx files from a source folder and have it renamed by appending "_Report" (vb script code)
I am using following code :
objFSO.CopyFile srcpath&"*.xlsx",destpath&"*_Report.xlsx",True
but it is not working. could anyone help me?
Just give a try for this script :
Option Explicit
Dim File,SourceFolder,DestinationFolder,Ws
SourceFolder = Browse4Folder()
DestinationFolder = SourceFolder & "\NewFolder"
Call BuildFullPath(DestinationFolder)
Call Scan4Folder(SourceFolder)
MsgBox "The script is finished by Hackoo !",VbInformation,"The script is finished by Hackoo !"
Set Ws = CreateObject("wscript.shell")
ws.run "Explorer " & DblQuote(DestinationFolder)
'**************************************************************************
Function Browse4Folder()
Dim objShell,objFolder,Message
Message = "Please select a folder "
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(0,Message,0,0)
If objFolder Is Nothing Then
Wscript.Quit
End If
Browse4Folder = objFolder.self.path
End Function
'*********************************************************************
Function Scan4Folder(Folder)
Dim fso,objFolder,File
Dim Tab,aFile,NewFileName
Set fso = CreateObject("Scripting.FileSystemObject")
Set objFolder = fso.GetFolder(Folder)
For Each File in objFolder.Files
NewFileName = GetNewName(File)
If UCase(fso.GetExtensionName(File)) = "XLSX" or UCase(fso.GetExtensionName(File)) = "XLS" Then
Msgbox "The File " & DblQuote(File) & " is copied on " & vbcr &_
DblQuote(DestinationFolder & "\" & NewFileName),vbInformation,DblQuote(File)
fso.CopyFile File,DestinationFolder & "\" & NewFileName
End If
Next
End Function
'*********************************************************************
Sub BuildFullPath(ByVal FullPath)
Dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(FullPath) Then
BuildFullPath fso.GetParentFolderName(FullPath)
fso.CreateFolder FullPath
End If
End Sub
'*********************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'*********************************************************************
Function GetNewName(sFile)
Dim fso,snamebase,AppendName,Ext
set fso = CreateObject("Scripting.FileSystemObject")
snamebase = Split(Right(sFile, Len(sFile) - InStrRev(sFile,"\")),".")(0)
AppendName = "_Report"
Ext = fso.GetExtensionName(sFile)
GetNewName = snamebase & AppendName & "." & Ext
End Function
'******************************************************************************
Please read the documentation for FSO.CopyFile.
It says that in the destination path
Wildcard characters are not allowed.

Convert A Robocopy Command to VB Script

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

Zip a folder up

I am trying to ZIP up a folder in VBScript and it doesn't seem to work. I'm certain I am creating the header file correctly.
It creates the actual file correctly, just doesn't zip the folder.
Anyone got any ideas:
Sub ArchiveFolder (folder)
Dim fso, wShell, sApp, zipFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set wShell = CreateObject("WScript.Shell")
Set sApp = CreateObject("Shell.Application")
Set zipFile = fso.CreateTextFile(folder & ".zip")
' Write zip file header.
zipFile.Write "PK" & Chr(5) & Chr(6) & String(18, 0)
zipFile.Close
sApp.NameSpace(folder & ".zip").CopyHere folder
End Sub
The answer I found here. The magic is in the last Do..Loop where the script wait the Shell to do it job.
ArchiveFolder "sub\foo.zip", "..\baz"
Sub ArchiveFolder (zipFile, sFolder)
With CreateObject("Scripting.FileSystemObject")
zipFile = .GetAbsolutePathName(zipFile)
sFolder = .GetAbsolutePathName(sFolder)
With .CreateTextFile(zipFile, True)
.Write Chr(80) & Chr(75) & Chr(5) & Chr(6) & String(18, chr(0))
End With
End With
With CreateObject("Shell.Application")
.NameSpace(zipFile).CopyHere .NameSpace(sFolder).Items
Do Until .NameSpace(zipFile).Items.Count = _
.NameSpace(sFolder).Items.Count
WScript.Sleep 1000
Loop
End With
End Sub
Check your argument. folder must be the path to the object you want to put into the zip file. If it's a folder object you have to use folder.Path, because the default method of folder objects is Name, and CopyHere can't find the object with just the name.
You could add some debugging statements to your function to check that:
WScript.Echo TypeName(folder)
If fso.FolderExists(folder) Then
WScript.Echo folder & " exists."
Else
WScript.Echo folder & " doesn't exist."
End If
you could call an external zip file via %comspec%
oShell.Run "%comspec% /c c:\windows\7za.exe a " & oFile &".zip " & oFile & " -tzip",,True
Source http://www.scriptlook.com/zip-large-files-in-a-directory-2/

Resources