Ok .. lemme explain the whole code.
Code: VB
Option Explicit
Dim objFSO, objFolder, objShell, objTextFile, objFile
Dim strDirectory, strFile, strText
strDirectory = "e:\logs3"
strFile = "\Summer.txt"
strText = "Book Another Holiday"
' Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
The above code-segment does mostly initialization stuff and is pretty obvious.
Code: VB
' Check that the strDirectory folder exists
If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
WScript.Echo "Just created " & strDirectory
End If
The above code checks for existence of
strDirectory. If it exists, that's good .. the script creates a folder object that represents
strDirectory, else .. it creates the directory.
Now, about your question .. "
I don't understand the results of this and what is the need for strDirectory when you can go immediately to the source."
Well, yeah you can
go immediately to the source if it
exists, else you would end up getting a run-time error that the specified path was not found !
Code: VB
If objFSO.FileExists(strDirectory & strFile) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
Wscript.Echo "Just created " & strDirectory & strFile
End If
The above segment similarly checks for the existence of strFile and creates it if it's not found.
Always remember to check for paths before trying to access them, that would ensure smooth and error-free running of your program.
Code: VB
set objFile = nothing
set objFolder = nothing
As
objFile and
objFolder are no longer required, unload them from memory.
Code: VB
' OpenTextFile Method needs a Const value
' ForAppending = 8 ForReading = 1, ForWriting = 2
Const ForAppending = 8
Set objTextFile = objFSO.OpenTextFile _
(strDirectory & strFile, ForAppending, True)
' Writes strText every time you run this VBScript
objTextFile.WriteLine(strText)
objTextFile.Close
Pretty obvious .. gets a text-stream from
strFile and then writes
strText to it.
Code: VB
' Bonus or cosmetic section to launch explorer to check file
If err.number = vbEmpty then
Set objShell = CreateObject("WScript.Shell")
objShell.run ("Explorer" &" " & strDirectory & "\" )
Else WScript.echo "VBScript Error: " & err.number
End If
WScript.Quit
Shells a Windows Explorer to let the user verify that the file exists.
I hope things are clear to you now.
No probs if not, keep posting