Tuesday, July 12, 2011
Scripting Techniques
1. Linear
2. Structured
3. Shared
4. Data Driven
5. Keyword Driven
Thursday, October 14, 2010
Build in Functions
IsNumeric Function
IsDate Function
Year Function
Date Function
Time Function
IsNumeric Function: Evaluates whether an expression can be converted to Date or Not.
Example:
Dim MyVar, MyCheck
MyVar = 53 ' Assigns a Numeric value.
MyCheck = IsNumeric(MyVar) ' Returns True.
MsgBox MyCheck
MyVar = "459.95" ' Assigns a String which consists of Number
MyCheck = IsNumeric(MyVar) ' Returns True.
MsgBox MyCheck
MyVar = "45 Help" ' Assigns a String.
MyCheck = IsNumeric(MyVar) ' Returns False.
MsgBox MyCheck
IsDate Function: Evaluates whether an expression is a number or not.
Example:
Dim MyDate, YourDate, NoDate
MyDate = "October 19, 1962": YourDate = #10/19/62#: NoDate = "Hello"
Msgbox "Value of MyDate is "&IsDate(MyDate)
Msgbox "Value of Your Date is "&IsDate(YourDate)
Msgbox "Value of NoDate variable is "&IsDate(NoDate)
Year Function: Returns the whole number representing an Year
Dim MyDate, MyYear
MyDate = #October 19, 1962# ' Assign a date.
MyYear = Year(MyDate) ' MyYear contains 1962.
Date Function: Returns the current system date.
MyDate = Date
Msgbox "Today's Date is "&MyDate
Time Function: Returns the current system time.
MyTime = Time
Msgbox "Current Time is "&MyTime
Tuesday, October 5, 2010
Input Box
Example:
Input = InputBox("Input Something","Title of the Input Box","Default Text in the Input Box")
Msgbox ("You Entered " & Input)
Wednesday, September 29, 2010
VBScript - XML Object
Inner text and Inner xml of XML file
Details of a single node
'Create an XML file
Set oXMLDoc = CreateObject("Microsoft.XMLDOM")
Set oRoot = oXMLDoc.createElement("Employees")
oXMLDoc.appendChild oRoot
Set oRecord = oXMLDoc.createElement("Employee")
oRoot.appendChild oRecord
Set oSSN = oXMLDoc.createElement("SSN")
oSSN.Text = "123456789"
oRecord.appendChild oSSN
Set oName = oXMLDoc.createElement("Name")
oName.Text = "Thanvi"
oRecord.appendChild oName
Set oDOB = oXMLDoc.createElement("DOB")
oDOB.Text = "2009-19-06"
oRecord.appendChild oDOB
Set oSalary = oXMLDoc.createElement("Salary")
oSalary.Text = 1000000
oRecord.appendChild oSalary
Set oIntro = oXMLDoc.createProcessingInstruction("xml","version='1.0'")
oXMLDoc.insertBefore oIntro,oXMLDoc.childNodes(0)
oXMLDoc.Save "C:\Employees.xml"
'Get the Inner text and Inner xml of the XML file
Set oXML = CreateObject("Microsoft.XMLDOM")
oXML.async = "false"
oXML.load("C:\Employees.xml")
msgbox "XML of the file "&oXML.xml
msgbox "Inner text of the xml file "&oXML.text
'Get the details of a single node
Set oXML = CreateObject("Microsoft.XMLDOM")
oXML.async = "false"
oXML.load("C:\Employees.xml")
Set MyNode = oXML.SelectSingleNode("/Employees/Employee/Name")
Msgbox "XML of the single Node "&MyNode.xml
Msgbox "Inner Text of the single Node "&MyNode.text
Msgbox "Type of the Node "&MyNode.nodeType
Tuesday, September 21, 2010
Sample Scripts
A(0) = 10
A(1) = 20
A(2) = 30
For i = 0 to 2
msgbox A(i)
Next
'Using String Array
StringArray(0) = "ArrayVariable1"
StringArray(1) = "ArrayVariable2"
StringArray(2) = "ArrayVariable3"
For i = 0 to 2
msgbox StringArray(i)
Next
'Split a string
Dim StringName, SplitString
StringName = "My name is xxx. I studied 10th class. I completed intermediate"
SplitString = split(StringName, " ")
For i = 0 to ubound(SplitString(i))
msgbox SplitString(i)
Next
'or
For i = LBound(SplitString) to UBound(SplitString)
msgbox SplitString(i)
Next
' Gets the Current Date, Current Time
Dim TodaysDate, CurTime, CurDateTime
TodaysDate = Date
CurTime = Time
CurDateTime = Now
msgbox "Today's Date "&TodaysDate
msgbox "Current Time "&CurTime
msgbox "Current Date and Time "&Now
Sunday, September 5, 2010
File System Object Vs Files
Type of the File
File Information
Copy a file
Move a file
Delete a file
Create a Text File
Appending Text to File
Reads Specified Number of characters from a Text File
Reads all the characters from a Text File
Reads the Text File Line by Line
Writes Text to a File
Writes Blank Line to a File
Column Number of current character position
Line Number of current position
'Syntax:
'OpenTextFile
'OpenTextFile(filename[, iomode[, create[, format]]])
'iomode:
'ForReading - 1 - Opens a file for Read Only
'ForWriting - 2 - Opens a file for Reading and Writing
'ForAppending - 8 - Opens a file for Appending
Delete
FileObject.Delete(force)
'force is boolean value
True - Files with Read-Only attribute is deleted
Move
FileObject.Move(Destination)
File Type
'0 - Normal File
'1 - Read Only File
'2 - Hidden File
'4 - System File
'8 - Volume File - Disk Drive Volume Label
'16 - Folder or Directory
'32 - Archieve - File has changed
'1024 - Alias
'2048 - Compressed File
Dim fso, f, s
Dim PathOfTheFile
PathOfTheFile = "C:\NewDebug.xml"
Set fso = CreateObject("Scripting.FileSystemObject")
Set FileInfo = fso.GetFile(PathOfTheFile)
AttrVal = FileInfo.Attributes
If AttrVal = 1 then
Msgbox "Normal File"
Else
Msgbox "Not a Normal File"
End If
File Information
Dim fso, f, s
Dim PathOfTheFile
PathOfTheFile = "C:\Documents and Settings\...\Desktop\NewDebug.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set FileInfo = fso.GetFile(PathOfTheFile)
s = "Date on which the file is Created: "&FileInfo.DateCreated &vbcrlf
s = s & "Date on which the file is Last Accessed: "&FileInfo.DateLastAccessed&vbcrlf
s = s & "Date on which the file is Last Modified: "&FileInfo.DateLastModified & vbcrlf
s = s & "Drive on which the file is Saved: "&FileInfo.Drive & vbcrlf
s = s & "Name of the file: "&FileInfo.Name & vbcrlf
s = s & "Name of the folder on which the file is saved: "&FileInfo.ParentFolder&vbcrlf
s = s & "Path of the file: "&FileInfo.Path&vbCrlf
s = s & "Short Name of the file: "&FileInfo.ShortName&vbcrlf
s = s & "Short Path of the file: "&FileInfo.ShortPath & vbcrlf
s = s & "Total Size of the file: "&FileInfo.Size & vbcrlf
s = s & "Type of the file: "&FileInfo.Type
msgbox s
'Copy a file from One location to Another location
Set objFSO = CreateObject("Scripting.FileSystemObject")
SourceFilePath = "D:\debugnew.txt"
DestinationFilePath = "D:\debugnew1.txt"
Set objFileCopy = objFSO.GetFile(SourceFilePath)
If objFSO.FileExists(DestinationFilePath)Then
objFileCopy.Copy(DestinationFilePath)
End If
'Move a file from One location to Another location
Set objFSO = CreateObject("Scripting.FileSystemObject")
SourceFilePath = "d:\debugnew.txt"
DestinationFolder = "C:\"
Set SourceFile = objFSO.GetFile(SourceFilePath)
SourceFile.Move DestinationFolder
'Delete a file
Set objFSO = CreateObject("Scripting.FileSystemObject")
FilePath = "D:\debugnew.txt"
Set objFile = objFSO.GetFile(FilePath)
If objFSO.FileExists(FilePath)Then
objFile.Delete
End If
'Create a text file
Dim fso, tf
Set fso = CreateObject("Scripting.FileSystemObject")
Set Textfile = fso.CreateTextFile("C:\FileName.txt",True)
Textfile.WriteLine("First Sentence")
Textfile.Close
Set Textfile = Nothing
Set fso = Nothing
'Appending Text to File
Dim ForAppending, fso, TextFile
ForAppending = 8
Set fso = CreateObject("Scripting.FileSystemObject")
Set TextFile = fso.OpenTextFile("C:\FileName.txt",ForAppending)
TextFile.WriteLine("Fail")
TextFile.Close
Set TextFile = Nothing
Set fso = Nothing
'Reading Text from File
Const ForReading =1, ForWriting = 2, ForAppending = 8
Set fso = CreateObject("Scripting.FileSystemObject")
Set TextFile = fso.OpenTextFile("C:\FileName.txt",ForReading)
Text=TextFile.Read(10) 'Reads first 10 characters
Msgbox "First 10 characters of file is "&Text
TextFile.Close
Set TextFile = Nothing
Set fso = Nothing
'Reading All the Text from File
Const ForReading =1, ForWriting = 2, ForAppending = 8
Set fso = CreateObject("Scripting.FileSystemObject")
Set TextFile = fso.OpenTextFile("C:\FileName.txt",ForReading)
Text=TextFile.ReadAll 'Reads entire file
Msgbox "File Contents "&Text
TextFile.Close
Set TextFile = Nothing
Set fso = Nothing
'Reading Text File Line by Line
Const ForReading =1, ForWriting = 2, ForAppending = 8
Set fso = CreateObject("Scripting.FileSystemObject")
Set TextFile = fso.OpenTextFile("C:\FileName.txt",ForReading)
linecount = 0
Text = ""
Do While TextFile.AtEndOfStream <> True
linecount = linecount + 1
Text=Text&"line "&linecount&" "&TextFile.ReadLine&vbCrLf
Loop
Msgbox "File Contents "&Text
TextFile.Close
Set TextFile = Nothing
Set fso = Nothing
'Writes Text to a File
Const ForReading =1, ForWriting = 2, ForAppending = 8
Set fso = CreateObject("Scripting.FileSystemObject")
Set TextFile = fso.OpenTextFile("C:\FileName.txt",ForWriting, True)
TextFile.Write "This is a new String of Data"
TextFile.Close
Set TextFile = Nothing
Set fso = Nothing
'Writes Blank Line to a File
Const ForReading =1, ForWriting = 2, ForAppending = 8
Set fso = CreateObject("Scripting.FileSystemObject")
Set TextFile = fso.OpenTextFile("C:\FileName.txt",ForWriting, True)
TextFile.WriteBlankLines(3) 'Writes 3 Blank Lines to the Text File
TextFile.Write "This is a new String of Data"
TextFile.Close
Set TextFile = Nothing
Set fso = Nothing
Column Number of current character position
Const ForReading =1, ForWriting = 2, ForAppending = 8
Set fso = CreateObject("Scripting.FileSystemObject")
Set TextFile = fso.OpenTextFile("C:\FileName.txt",ForWriting, True)
Text = TextFile.ReadLine
ColNum = Text.Column
TextFile.Close
Set TextFile = Nothing
Set fso = Nothing
'Line Number of current position
Const ForReading =1, ForWriting = 2, ForAppending = 8
Set fso = CreateObject("Scripting.FileSystemObject")
Set TextFile = fso.OpenTextFile("C:\FileName.txt",ForReading, True)
Text = TextFile.ReadAll
LineNum = Text.Line 'Gets the Last Line Number
msgbox "Number of Lines in the Text File "&LineNum
TextFile.Close
Set TextFile = Nothing
Set fso = Nothing
Working with Excel Object
Set ExcelObject = CreateObject("Excel.Application")
ExcelObject.visible = True
ExcelObject.WorkBooks.Add 'Adds a workbook to an excel object
ExcelObject.Sheets(1).Cells(1,1).value = "Text in the Cell" 'Writes a text to a particular cell in the excel object
'Open Microsoft file using VBScript
Set ExcelObject = CreateObject("Excel.Application")
ExcelObject.visible = True
ExcelObject.Workbooks.Open("c:\excelsheet.xls",Default, False)
ExcelObject.Sheets(1).Cells(1,1).value = "Text to be entered"
ExcelObject.Activeworkbook.SaveAs("d:\excelsheet.xls") 'Using Save As
'Save the Excel Workbook
ExcelObject.Activeworkbook.save
'Get the Number of Rows used in the Excel sheet
RowCount = ExcelObject.ActiveWorkbook.Sheets(1).UsedRange.Rows.count
msgbox "Number of rows used in the excel sheet "& RowCount
'Get the Number of Columns used in the Excel sheet
ColumnCount = ExcelObject.ActiveWorkbook.Sheets(1).UsedRange.Columns.count
msgbox "Number of columns used in the excel sheet "&ColumnCount
'Change the sheet name of the Excel workbook
ExcelObject.Activeworkbook.Sheets(1).Name = "NameOftheFirstSheet"
ExcelObject.Activeworkbook.Sheets(2).Name = "NameoftheSecondSheet"
'Get the Sheet Name of the Excel workbook
FirstSheetName = ExcelObject.Activeworkbook.Sheets(1).Name
msgbox "Name of the first sheet"&FirstSheetName
SecondSheetName = ExcelObject.Activeworkbook.Sheets(2).Name
msgbox "Name of the second sheet"&SecondSheetName
Thursday, September 2, 2010
Loop Statements in VBScript
Do...Loop: Loops while or until a condition is True
While...Wend: Loops while a condition is True
Syntax:
While condition
[statements]
Wend
For...Next: Uses a counter to run statements a specified number of times.
For Each ...Next: Repeats a group of statements for each item in a collection or each element of an array.
'Do ... While Statement
Count = 1
Do While Count <= 10 msgbox Count Count = Count + 1 Loop Do Statement
Count =1
Do
msgbox Count
Count = Count + 1
Loop While(Count <= 10)
'For...each statement
Dim Names(2)
Names(0) = "Tove"
Names(1) = "Jani"
Names(2) = "Hege"
For each Name in Names
msgbox (Name)
Next
'For statement
for counter = 0 to 5
msgbox "The counter value is "&counter
next
VBScript - MS Word
'Create a word Document
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
'Documents collection includes all of the open documents.
'Add method is used to create a blank document.
'Document object returned by Add method is assigned to a variable, objDoc.
Set objDoc = objWord.Documents.Add()
'Open a word Document file
Set wrd = CreateObject("Word.Application")
wrd.Visible = True
'To open an existing document, use the Open method with the Documents collection.
'The following instruction opens a document "Temp.doc" located in the folder "D:\"
wrd.Documents.Open "D:\Temp.doc"
Set wrd.Nothing
'Writting a Text in Word Application
Set oWord = CreateObject("Word.Application")
oWord.Visible = True
Set oDoc = oWord.Documents.Add()
Set oSelection = oWord.Selection
'Selection property represents selected area in a document or an insertion point
oSelection.TypeText = "Sample Text"
'Formatting the text in the word document
Set oWord = CreateObject("Word.Application")
oWord.Visible = True
Set oDoc = oWord.Documents.Add()
Set oSelection = oWord.Selection
'Setting the Font Name
oSelection.Font.Name = "Arial"
'Setting the Font Size
oSelection.Font.Size = "20"
'Setting the type face to Bold
oSelection.Font.Bold = True
oSelection. ParagraphFont.Alignment = 1
'0 - Aligns text to Left, 1- Aligns text to center
'2 - Aligns text to Right, 3 - Justify the text
oSelection.TypeText = "Add your text here"
'Replacing a Word in Word Document
Set oWord = CreateObject("Word.Application")
Set oDoc = oWord.documents.Open("C:\WordDocument.docx")
Set oWords = oDoc.Words
For word = 1 to oWords.Count
oWords.Item(word).Text = Replace(oWords.Item(word).Text, "sample","New word")
Next
oDoc.Save
oDoc.Close
oWord.Quit
Set oDoc = Nothing
Set oWords = Nothing
Set oWord = Nothing
'Saving the Word Document
To save a single doucument use the Save method with the Document object. The following insturction saves the document named "Sales.doc"
Documents("Sales.doc")Save
You can save all open documents by applying Save method to the Documents collection. The following instruction saves all open documents.
Documents.Save
'To save to a new location use "SaveAs" else use "Save" method to save it on default location
oDoc.SaveAs("c:\MyDoc.doc")
'Closing the Word Document
oWord.Quit
'Working with Tables
Set oWord = CreateObject("Word.Application")
oWord.visible = True
Set oDoc = oWord.Documents.Add()
Set oRange = oDoc.Range()
oDoc.Tables.Add oRange,3,3
Set oTable = oDoc.Tables(1)
For Row = 1 to 3
For Column = 1 to 3
oTable.Cell(Row,Column).Range.Text = Row&" Row, "&Column&" Column"
Next
Next
'Make the First Row Data to Bold
oTable.Rows.Item(1).Range.Font.Bold = True
'Makes the First Row Data to Italic
oTable.Rows.Item(1).Range.Font.Italic = True
'Changes the font size
oTable.Rows.Item(1).Range.Font.Size = 12
'Sets the width of the Column
oTable.Columns.Item(1).SetWidth 100,0
'Open and Append Text to a Document
Dim oWord
Set oWord = CreateObject("Word.Application")
oWord.Documents.Open "c:\text.doc"
oWord.Selection.TypeText "Text which is appended to existing document"
oWord.ActiveDocument.Save
oWord.Quit
Set oWord = Nothing
Selection property by default appends the text at the beginning only. To put the statements for selection at the end before entering the text, use the below cose.
Dim oWord
Set oWord = CreateObject("Word.Application")
oWord.Documents.Open "c:\text.doc"
oWord.Selection.EndKey 6,0
oWord.Selection.TypeText "Text which is appended to existing document"
oWord.ActiveDocument.Save
oWord.Quit
Set oWord = Nothing
'EndKey method moves the selection to the specified unit.
'Two parameters are unit and Extend. We have used 6 for unit
'which is to move at the end of story & 0 as extend which is to move the selection.
'If you don't specify these parameters, selection moves to the end of line.
'Prints the word document
Dim oWord
Set oWord = CreateObject("Word.Application")
oWord.Documents.Open "c:\test.docx"
oWord.Activedocument.PrintOut
oWord.Quit
Set oWord = Nothing
Conditional Statements
If Statement
Select Statement
syntax:
Select case testexpression
[case expression-list-n
[statements-n]]...
[case else
[elsestatements-n]]
End Select
'Script for select case statement
day1 = weekday(date)
select case day1
case 1
msgbox("Sleepy Sunday!")
case 2
msgbox("Monday again!")
case 3
msgbox("Just Tuesday!")
case 4
msgbox("Wednesday!")
case 5
msgbox("Thursday...")
case 6
msgbox("Finally Friday!")
case else
msgbox("Super Saturday!!!!!")
end select
If...Else...Statement
Syntax:
If statement takes the following format
{simple format} If condition Then statement(s) [else elsestatement(s)]
{block format}
If condition Then
[elseif condition then
[elseif statement(s)]]...
[else
[elsestatement(s)]]
End If
Script using if...else statement
timenow = hour(time)
if timenow = 10 then
msgbox("Just started...!")
elseif timenow = 11 then
msgbox("Hungry")
elseif(timenow = 12)then
msgbox("Ah, lunch-time")
elseif timenow = 16 then
msgbox("Time to go home!")
else
msgbox("Unknown")
end if
Data Types
Variant can contain one of the following types
Empty - Variant is uninitialised. Value is 0 for numeric variables or a zero-length string ("") for string variables
Null - Intentionally contains no valid data
Boolean - Contains either True or False
Byte - Contains integer in the range 0 to 255
Integer - Contains integer ranging from 0 to 255
Currency - Contains values between -922,337, 203, 685, 477.5808 to 922,337, 203, 685, 477.5807
Long - Contains integer in the range -2,147,483,648 to 2,147,483,647
Single - Contains a single-precision
Double - Contains a double-precision
Date - Contains a number that represents a date between January 1, 100 to December 31, 9999.
String - Contains a variable-length string that may approximately contain 2 billion characters in length
Object - Contains an object
Error - Contains an error number
Using Variables
Declaring Variables
Declaring a single variables
Declaring Multiple variables
Declaring a single variables
We can declare variables using Dim statement or public statement or private statement
Example:
Dim Variable1
public Variable2
private Variable3
Declaring Multiple variables
We can declare multiple variables by separating each variable name with a comma.
Example:
Dim Coordx, Coordy, Coordz
Standard Rules for Variable Names
- Must begin with an alphabetic character (A...Z,a...z) or an underscore character
- Cannot contain an embedded period
- Must not exceed 255 characters
- Must be unique in the scope in which it is declared.
- After the first character, variable can contain letters, digits and underscore
Assigning value to Variables
Variable1 = 10
Variable Constants
We can create variable constants using const keyword.
Const Pi = 3.14
Array VariablesAn array variables is used to store multiple values in a single variable.
Dim VehicleName(2)
VehicleName(0) = "Volvo"
VehicleName(1) = "Santro"
VehicleName(2) = "Mahindra"
Simple Tasks in VBScript
somedate = "10/30/99"
msgbox(IsDate(somedate))
'Script for converting a string into upper case and lower case
txt = "Have a nice day!"
msgbox(ucase(txt))
msgbox(lcase(txt))
'Script for removing the spaces before and after the string
name = " Bill "
msgbox("Hello" & trim(name) & "Gates")
msgbox("Hello" & rtrim(name)& "Gates")
msgbox("Hellow"<rim(name)&"Gates")
'Script for reversing a string
sometext = "Hello Everyone!"
msgbox(strReverse(sometext))
'Script for rounding a number to nearest integer
i = 48.66776677
j = 48.33333333
msgbox(Round(i))
msgbox(Round(j))
'Script for getting the Left and Right characters from the given string
sometext = "Welcome to our Web Site!!"
msgbox(Left(sometext,5))
msgbox(Right(sometext, 5))
'Script for getting the specified number of characters from the given position
sometext = "Welcome to our Web Site!!"
msgbox(Mid(sometext,6,2))
Constants
A Constant is an item that holds the data but cannot change during the execution of program.
VBScript supports two types of constants.
1. Implicit Constants: Implicit constants are pre-defined by VBScript. Implict constants begin with a vb prefix.
Example: Color Constants, Date and Time Constants, MsgBox Constants
2. Explicit Constants: Explicit constants are defined by the programmer
Tuesday, June 8, 2010
VBScript - Dictionary Object
Remove All
Remove
Key exists
Add an Item to Dictionary
Set oDictionary = CreateObject("Scripting.Dictionary")
oDictionary.Add "a","Akhila" 'Adds a item and key pair
oDictionary.Add "b","Bhanu"
oDictionary.Add "d","Deepthi"
MsgBox "The number of key/item pairs "&oDictionary.Count
For Each obj in oDictionary
msgbox "The key for "&obj&" and the associated data is "&oDictionary(obj)
Next
Msgbox "The value of key a is "&oDictionary.Item("a")
Determine if a specified key exists in the Dictionary Object
Set oDictionary = CreateObject("Scripting.Dictionary")
oDictionary.Add "a","Akhila" 'Adds a item and key pair
oDictionary.Add "b","Bhanu"
if oDictionary.Exists("b") Then msgbox "Key exists in the Dictionary"
Remove a key/item pair from Dictionary Object
Set oDictionary = CreateObject("Scripting.Dictionary")
oDictionary.Add "a","Akhila" 'Adds a item and key pair
oDictionary.Add "b","Bhanu"
oDictionary.Add "d","Deepthi"
oDictionary.Remove("b")
Removes all key/item pairs from Dictionary Object
Set oDictionary = CreateObject("Scripting.Dictionary")
oDictionary.Add "a","Akhila" 'Adds a item and key pair
oDictionary.Add "b","Bhanu"
oDictionary.Add "d","Deepthi"
oDictionary.RemoveAll
Friday, May 14, 2010
Working with File System Object 1
Dim verNum
Set objFSO = CreateObject("Scripting.FileSystemObject")
verNum= objFSO.GetFileVersion("C:\Program Files\Mozilla Firefox\firefox.exe")
MsgBox("Firefox Version"&verNum)
Thursday, May 13, 2010
File System Object Vs Folders
Size a Folder
Copy a Folder
Move a Folder
Delete a Folder
File Count in a folder
SubFolder Count in a Folder
Add a New Folder
Filenames in a folder
SubFoldernames in a Folder
'Syntax:
Copy
FolderObject.Copy(destination[, overwrite])
MoveFolder
FolderObject.MoveFolder(source, destination)
Delete a Folder
FolderObject.DeleteFolder(folderspec[, false])
'Size a Folder
Dim SourceFolder, oFSO
SourceFolder = "C:\IM"
Set oFSO = CreateObject("Scripting.FileSystemObject")
oFSO.GetFolder(SourceFolder)
Msgbox "Size of the Folder "&oFSO.Size&" bytes" 'Display the size of the folder
'Copy a Folder
Dim SourceFolder, oFSO
SourceFolder = "C:\IM"
Set oFSO = CreateObject("Scripting.FileSystemObject")
oFSO.CopyFolder SourceFolder, "D:\"
'Move a Folder
Dim SourceFolder, DestinationFolder, oFSO
SourceFolder = "C:\IM"
DestinationFolder = "D:\"
Set oFSO = CreateObject("Scripting.FileSystemObject")
oFSO.MoveFolder SourceFolder, DestinationFolder
'Delete a Folder
Dim SourceFolder, oFSO
SourceFolder = "D:\IM"
Set oFSO = CreateObject("Scripting.FileSystemObject")
oFSO.DeleteFolder SourceFolder
'Get the File Count in a folder
Set FSO = CreateObject("Scripting.FileSystemObject")
FolderPath = "C:\Documents and Settings\"
Set TestFolder = FSO.GetFolder(FolderPath)
Set Files = TestFolder.Files
MsgBox("Number of Files in:"&vbCrLf&FolderPath&vbcrlf&Files.Count)
'Get the SubFolder Count in a Folder
Set FSO = CreateObject("Scripting.FileSystemObject")
Set TestFolder = FSO.GetFolder("C:\Documents and Settings")
Set SubFolders = TestFolder.SubFolders 'Returns the collection of subfolders
Msgbox(SubFolders.Count)
'Add a New Folder
Sub AddNewFolder(FolderPath, FolderName)
Dim FSO, f, fc,nf
Set FSO = CreateObject("Scripting.FileSystemObject")
Set f = FSO.GetFolder(FolderPath)
Set fc = f.SubFolders
If FolderName <> "" Then
Set nf = fc.Add(FolderName)
Else
Set nf = fc.Add("New Folder")
End If
End Sub
AddNewFolder "C:\",""
'Filenames in a Folder
Folderpath = "C:\MyFolder"
Dim FSO, oFolder
Set FSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = FSO.GetFolder(FolderPath)
Files = oFolder.Files 'Gets the collection of files in a folder
For each file in Files
Msgbox File.Name
Next
'SubFoldernames in a Folder
Folderpath = "C:\MyFolder"
Dim FSO, oFolder
Set FSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = FSO.GetFolder(FolderPath)
Folders = oFolder.SubFolders 'Gets the collection of subfolders in a folder
For each folder in Folders
Msgbox folder.Name
Next
File System Object Vs Drives
Drive Information
Drive Name of a specified file path
Drive is Ready or Not
'Total Number of Drives in your System
Set FSO = CreateObject("Scripting.FileSystemObject")
Set DriveCollection= FSO.Drives 'A collection of drive objects
MsgBox("Total Number of Drives available in your system: "&DriveCollection.Count)
'Drive Information in your System
Set FSO = CreateObject("Scripting.FileSystemObject")
intDrive = 0
For Each Driver in FSO.Drives
Msgbox "Name of the Drive :"&Driver.DriveLetter
Select Case Driver.DriveType
Case 0: strDriveType = "Drive type cannot be determined"
Case 1: strDriveType = "Removable Drive"
Case 2: strDriveType = "Fixed Drive"
Case 3: strDriveType = "CD-ROM"
Case 4: strDriveType = "RAM Disk"
End Select
msgbox "Type of the Drive : "&strDriveType
If(Driver.DriveType = 2)Then
msgbox "Total Size of the Specified Drive: "&Driver.Totalsize
msgbox "Free Space available in the Drive: "&Driver.FreeSpace
msgbox "Available Space in the Drive: "&DriverAvailableSpace
msgbox "File System of the specified Drive: "&Driver.FileSystem
'Available File Systems are FAT, NTFS and CDFS
msgbox "Serial Number of the specified Drive: "&Driver.SerialNumber
msgbox "Share Name of the specified Drive: "&Driver.ShareName
msgbox "Volume Name of the specified Drive: "&Driver.VolumeName
End If
intDrive = intDrive + 1
Next
'Drive Name of a specified file path
DrvPath = "D:\debugnew.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set GetDriveInfo = fso.GetDriveName(drvPath)
Msgbox ("Name of the Drive :"&GetDriveInfo)
'Drive is Ready or Not
DrvPath = "D:\debugnew.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set GetDriveInfo = fso.GetDrive(fso.GetDriveName(drvPath))
If GetDriveInfo.IsReady Then
Msgbox "Drive is Ready"
Else
Msgbox "Drive is Not Ready"
End If
Tuesday, May 4, 2010
Comments
Example:
\'This is a single line comments
\''This is another single line comment