PowerShell Ezine, Logon Scripts

Guy's Scripting Ezine 78 - Create Files and Folders

Contents for Ezine 78 - Create Files and Folders

 ♣

This Week's Secret

I admit that I do not always take my own advice to build scripts gradually.  When I have a long script that is not working, I cannot resist taking a stab at the middle in an attempt to cure the error.  However, if I have not solved the problem in three goes, then I do practice what I preach and dissect the script into bite size chunks.  As far as is possible, I get each section working then paste them all together.

Incidentally, every day I get an average of 2 requests from people wanting help with their scripts. Now I say to them that my best initial advice is - simplify your script and isolate the error. The other side of the coin is that if you have a script that is working, then it suddenly seems easier to add extra features.

Scenario: You inherit a long script, but it does not work.

Following the popularity of FSO (File System Object) in previous ezines this week's script creates a folder then adds a file.

The situation is that you have to troubleshoot a script that someone else created.  Let us assume that the script is supposed to write data to a file, but when you execute the script, there is no file.  So, the solution is to breakdown the task into three stages.

  1. Create the Folder
  2. Create the File
  3. Write text to the File  (Next week's Project)

From a pure learning point of view, I want to show you how to create a FileSystemObject and then apply the .CreateFolder and .CreateTextFile methods.  Finally, once we can get a 'handle' on the file, we can write or append data.

Guy Recommends: Tools4ever's UMRAUMRA The User Management Resource Administrator

Tired of writing scripts? The User Management Resource Administrator solution by Tools4ever offers an alternative to time-consuming manual processes.

It features 100% auto provisioning, Helpdesk Delegation, Connectors to more than 130 systems/applications, Workflow Management, Self Service and many other benefits. Click on the link for more information on UMRA.

Prerequisites

This is a script that will execute equally well on a Windows server or an XP machine.  To ensure that there are no permissions errors, I recommend that you logon as administrator.

Instructions for Creating a Folder

  1. Copy and paste the example script below into notepad or a VBScript editor.
  2. Decide whether to change the value for strDirectory.
  3. Save the file with a .vbs extension, for example: CreateFolder.vbs 
  4. Double click CreateFolder.vbs and check your new folder.

Example 1 - Create the Folder

Here is the first stage of our project, namely to build a folder called d :\files.  Do change strDirectory if you don't like this name, or if you have no d: drive!

 

 

' CreateFolder.vbs
' Sample VBScript to create a folder.
' Author Guy Thomas http://computerperformance.co.uk/
' Ezine 78 Version 1.2 - July 2005
' ---------------------------------------------------------------'

Option Explicit
Dim objFSO, objFolder, objShell, strDirectory
strDirectory = "d:\files"

' Create the File System Object objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Check whether the strDirectory folder exists
If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else

' Here is the key method .CreateFolder
Set objFolder = objFSO.CreateFolder(strDirectory)
WScript.Echo "Just created " & strDirectory
End If

set objFolder = nothing
WScript.Quit

' End of VBScript to create a folder.

Learning Points

Note 1:  CreateObject holds the key.  What we want in this instance is FileSystemObject object suitable for making folders and files.  My point is that for this task, we don't need a network or an Active Directory object.

Note 2:  Now what we need here is a folder.  So, we apply the .CreateFolder method to the objFSO and thus ensure that we get the desired folder object (and not a file object).

Note 3:  The construction, If objFSO.FolderExists (strDirectory) is interesting and slightly unusual.  Interesting because FSO supports the .FolderExists method.  Unusual because not all objects support the 'Exists' family of methods.

Note 4:  Example 1 (above) is a proper script with error correcting code.  Whether the folder already exists, or whether the script creates the folder, VBScript cannot fail.  The WScript.Echo message is largely for testing, feel free to remove such lines from your production script.

Guy Recommends: The Free IP Address Tracker (IPAT) IP Tracker

Calculating IP Address ranges is a black art, which many network managers solve by creating custom Excel spreadsheets.  IPAT cracks this problem of allocating IP addresses in networks in two ways:

For Mr Organized there is a nifty subnet calculator, you enter the network address and the subnet mask, then IPAT works out the usable addresses and their ranges. 

For Mr Lazy IPAT discovers and then displays the IP addresses of existing computers.  Download the Free IP Address Tracker

Example 2 - Create the File

Here is stage 2, creating the file.  This script is a natural progression from Example 1 so,  I have left in the code which creates the folder and added code which creates the file.  As a bonus, I added a method to open explorer so that we could see the newly born file.

' CreateFolder.vbs
' Sample VBScript to create a folder and file.
' Author Guy Thomas http://computerperformance.co.uk/
' Ezine 78 Version 1.4 - July 2005
' ---------------------------------------------------------------'

Option Explicit
Dim objFSO, objFolder, objFile, strFile, objShell, strDirectory
strDirectory = "d:\Files"
strFile = "\GuySpecial.txt"

' Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")

' 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

' Key section employing the .CreateTextFile method.
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

set objFolder = nothing
set objFile = nothing

' Bonus section to display the file created
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

' End of VBScript to write to a file.

Learning Points

Note 1: The crucial extra code creates a file.  Remember that the method is called .CreateTextFile and not CreateFile.

Note 2: A tiny point, but the script produces an error when it's first run, unless I added set objFolder and objFile = nothing.  Here is an example where I always learn more when things go wrong.  I have known for a long time that I should nullify objects when I have finished them, but idleness and wanting to keep the script short have meant I have omitted these set objxyz = nothing from of other scripts.  Sometimes I get away with it, but not in this example.

Note 3: objShell = CreateObject("WScript.Shell") is my way of demonstrating that the script has achieved its goal.  The active part is objShell.run.  In this example, it is as if you clicked on the Start (Menu), Run and typed 'Explorer'.

Example 3 - To Write text into our File.

I thought long and hard and decided to split this topic into two.  There really are more than enough learning points already for one week.  Next week's ezine will feature writing text to files.

Summary for FSO

With VBScript you can create a FileSystemObject.  Once you have the FSO object then you can manipulate it with methods such as .CreateFolder and .CreateTextFile.  Incidentally these examples are a change from the usual GetObject or create network objects.

See more about scripting files with VBScript

VBScripts  • Ezines  • WMI  • Create files  • File Open  • Ezine 12 FSO  • Permissions Analyzer

• Ezine 35 FSO  • Ezine 36 FSO II  • Ezine 43 File Create  • PowerShell Create Files

Ezine 78 Files  • Ezine 79 Files  • Ezine 104 FSO  • Ezine 139 Delete Temporary

 


Custom Search

Site Home

Guy Recommends: WMI Monitor and It's Free!Solarwinds WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems.

Fortunately, SolarWinds have created the Free WMI Monitor so that you can actually see and understand these gems of operating system information.  Take the guess work out of which WMI counters to use for scripts.

Download your free copy of WMI Monitor

Author: Guy Thomas Copyright © 1999-2014 Computer Performance LTD All rights reserved.

Please report a broken link, or an error to: