Home > Articles > Home & Office Computing > Microsoft Windows Desktop

Like this article? We recommend

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 level—namely, 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 parameter—namely, 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 subroutines—self-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 functions—self-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 value—namely, 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020