- Representing a File in WMI
- WMI Dates and Times
- More About Files
- Manipulating Files
- File Compression
- Conclusion
Manipulating Files
In addition to providing information about the underlying objects that they represent, many WMI classes expose methods for controlling and manipulating those objects. CIM_DataFile is no exception. A reference to a CIM_DataFile object can be used to perform a number of simple housekeeping tasks on the file it represents. There are methods to support most of the actions you would expect to be supported at the filesystem levelnamely, copying, moving, renaming, and deleting. In addition, there are methods to control a file's compression status and to manipulate security on an NTFS filesystem.
The following script fragments demonstrate the use of these methods (with the exception of the security-related methods, which are somewhat beyond the scope of this article). Because some of these methods are really quite destructive, it is probably best not to use a file as important as boot.ini as the example if you intend to try anything out!
The Copy() method is invoked exactly as might be expected: It takes a single parameternamely, a string representing the destination path. So, assuming that refFile has been set to point to a valid CIM_DataFile, you could invoke Copy like this:
refFile.Copy "c:\temp\copy-of-file.txt"
Despite the evident simplicity, there are a few idiosyncrasies to note. First, the destination path must always be given in full; you may not omit the filename if you're copying to a different directory, and you may not omit the directory name if you're copying to a different filename in the same directory. After all, a CIM_DataFile has no concept of a "working directory." Second, the Copy() method cannot be used to overwrite an existing file. This limitation seems somewhat strange given that there are many circumstances under which overwriting a file with a copy operation is exactly what you want to do. No doubt Microsoft had its reasons. Another caveat is that the intended destination directory must exist, because it will not be created on-the-fly. This behavior, however, is unsurprising and should not catch too many people off guard!
The Rename() method can be used to either rename or move a file. Its invocation is identical to that of Copy(), and its use is subject to exactly the same limitations. The two uses are illustrated in the following script fragment, which invokes Rename on a refFile that has been previously initialized to represent "c:\temp\goose.txt":
'This command will rename the file as "albatross.txt" while 'leaving it in its current location refFile.Rename "c:\temp\albatross.txt" 'This command will move the file, preserving its name refFile.Rename "c:\matthew\goose.txt"
Invoking the Delete() method is even more straightforward, requiring no parameters:
refFile.Delete
Of course, there are a number of caveats to consider when invoking Delete() on a CIM_DataFile object, because the operations that can be performed by a file through WMI are subject to the same set of restrictions as those that govern file manipulation anywhere else. For example, you cannot delete a read-only file or one for which you do not have the relevant permissions. I will discuss mechanisms for detecting such problems in the next section.
In a real script, it is always sensible to dereference a CIM_DataFile object immediately after invoking its Delete() method (that is, set the relevant object reference to Nothing):
refFile.Delete Set refFile = Nothing
Failure to do this can lead to rather strange results. You can see this by using Notepad to create a file in c:\temp called deleteme.txt, adding a few lines of text, saving it, and then running the following script:
'deleteme.vbs - demonstrate strange delete behavior Set refFile = GetObject("winMgmts:CIM_DataFile.Name='c:\temp\deleteme.txt'") WScript.echo "Hello. I am a file called " & refFile.Name WScript.echo "I am about to be deleted" refFile.Delete WScript.echo "Hello again. I am still a file called " & refFile.Name WScript.echo "And I even have a size: " & refFile.FileSize WScript.echo "And now the program will crash..." refFile.Delete 'the line below will not be called set refFile = Nothing
This produces output very similar to the following:
Hello. I am a file called c:\temp\deleteme.txt I am about to be deleted Hello again. I am still a file called c:\temp\deleteme.txt And I even have a size: 28 And now the program will crash... C:\wmibook\oops.vbs(10,1) SWbemObject: Not found
Oops! Even after the file has been deleted, the CIM_DataFile object is more than happy to continue providing information about it, because this information is cached and can be read without reference to the underlying filesystem. You find out that something has gone dramatically wrong only when you attempt to carry out an action that forces the CIM_DataFile to interact with the underlying filesystem. At this point, the object realizes that it is nothing but a ghost, representing something that does not actually exist. WMI throws an error, and the script exits.
This scenario reveals something extremely important about WMI objects and their relationship with the underlying structures they represent: WMI objects are populated with data that is accurate at the time the object is constructed. If the underlying structure changes after this time, these changes will not be reflected in the WMI object.
An artifact of the same phenomenon is illustrated by the following code fragment:
WScript.Echo "My name is " & refFile.Name refFile.Rename "c:\temp\goose.txt" WScript.Echo "My new name is " & refFile.Name
If this code is called on a CIM_DataFile that represents a file called c:\temp\albatross.txt, its output would be
My name is c:\temp\albatross.txt My new name is c:\temp\albatross.txt
Despite the fact that the file is now really called goose.txt, the CIM_DataFile knows nothing of this novelty. In the trivial examples shown here, the mistakes are easy enough to spot, but in longer, more complex scripts, confusing mistakes are much easier to make. Luckily, you can avoid these pitfalls altogether by following one simple rule: If you invoke a method on an object that causes an inconsistency to appear between the object and the structure it represents, always dereference the WMI object immediately after the invocation. An attempt to access properties of a dereferenced object will cause VBScript to raise an error but will never lead to inconsistent, bizarre results.
Detecting Errors
An attempt to perform an operation on a nonexistent entity, such as invoking Delete() twice on a CIM_DataFile, causes WMI to raise an error that terminates script execution (unless it is handled). This reaction occurs because WMI encounters a situation with which it cannot cope. Not all failed operations evoke such drastic reactions, however. Under normal circumstances, a failed attempt to invoke Copy(), Move(), or Delete() appears to evoke no reaction at all. If, for example, an attempt is made to copy a file to a nonexistent directory, the copy will fail, but the WMI provider that is responsible for executing this method has been explicitly written to cope with such an eventuality and will not complain. To understand this point, try running the following script:
'silentfailure.vbs - demonstrate silent copy failure Option Explicit Dim refFile Set refFile = GetObject("winMgmts:CIM_DataFile.Name='c:\boot.ini'") WScript.Echo "About to do something stupid" refFile.Copy "z:\pterodactyl\triceretop\z\x\q.txt" WScript.echo "The script still seems to be running" Set refFile = Nothing
Unless you happen to have a directory on your system whose path is z:\pterodactyl\triceretop\z\x, the copy will undoubtedly fail, but the script will continue to run.
Although it is good to know that a failed copy or move operation will not crash a script, it is often equally good to know whether an operation succeeds! In common with many WMI methods, CIM_DataFile methods reveal this information in the form of a return value. So far, we have been using these methods as though they were subroutinesself-contained blocks of code that perform an action but return no value. As far as VBScript syntax is concerned, we have been invoking them as statements. However, it is equally possible to use them as functionsself-contained blocks of code that return a value. Syntactically, they would become VBScript expressions. Unlike our own GetVBDate() function, whose main purpose is to return a value, the primary purpose of the CIM_DataFile methods when used as functions is still to carry out an action, but as an added bonus, they return a valuenamely, an error code.
The following script, like its companion (just shown), is highly likely to fail:
'anotherfailure.vbs - another demonstration of copy failure Option Explicit Dim refFile Dim numErrorCode Set refFile = GetObject("winMgmts:CIM_DataFile.Name='c:\boot.ini'") numErrorCode = refFile.Copy("z:\pterodactyl\triceretop\z\x\q.txt") WScript.echo "Error code: " & numErrorCode Set refFile = Nothing
Running it produces the following output:
Error code: 9
According to the CIM_DataFile specification, this code means that "the name specified was invalid." The following table is a complete listing of error codes returned by CIM_DataFile methods, along with their meanings. All of these methods share the same collection of error codes, although clearly not all of them are applicable to every operation!
CIM_DataFile Method Error Codes
Code |
Meaning |
2 |
You do not have access to perform the operation. |
8 |
The operation failed for an undefined reason. |
9 |
The name specified as a target does not point to a real file or directory. |
10 |
The file or directory specified as a target already exists and cannot be overwritten. |
11 |
You have attempted to perform an NTFS operation on a non-NTFS filesystem. |
12 |
You have attempted to perform an NT/2000-specific operation on a non-NT/2000 platform. |
13 |
You have attempted to perform an operation across drives that can be carried out within only a single drive. |
14 |
You have attempted to delete a directory that is not empty. |
15 |
There has been a sharing violation. Another process is using the file you are attempting to manipulate. |
16 |
You are attempting to act on a nonexistent file. |
17 |
You do not have the relevant NT security privileges to carry out the operation. |
21 |
You have supplied an invalid parameter to the method. |
So far, we have been treating the file manipulation methods as subroutines. However, if instead we treat them as functions, we can read these error codes from within our script. The file manipulation methods, in common with virtually all WMI methods, present an error code as a return value. A value of 0 indicates a successful operation. A minor modification to our script, then, can make it report on the success or failure of the attempted operation:
'copycheck.vbs - copy a file, demonstrating use of error return code Dim numErrorCode Set refFile = GetObject("winMgmts:CIM_DataFile='c:\boot.ini'") numErrorCode = refFile.Copy("z:\pterodactyl\triceretop\z\x\q.txt") If numErrorCode = 0 then WScript.Echo "File copied successfully" Else WScript.Echo "Copy failed with error code " & numErrorCode End If Set refFile = Nothing
Of course, you could make this code more user-friendly by testing numErrorCode for each possible value and reporting in text format exactly which error occurred. For the moment, though, this hardly seems necessary.
Note that in this script and the immediately preceding one, the syntax of the Copy() invocation has changed to reflect the fact that we are using it as a function. Omitting the parentheses around its parameters would constitute a syntax error.