Recipe 8.1. Creating and Deleting a File


Problem

You want to create or delete a file.

Solution

Using a graphical user interface

  1. Open Windows Explorer.

  2. In the left pane, browse to the folder where you want to create the file or that contains the file you want to delete. Click on the folder.

  3. To create a new file, right-click in the right pane and select New and the type of file you want to create. To edit the file, double-click on it.

  4. To delete a file, right-click the file in the right pane and select Delete. Click Yes to confirm. This moves the file to the recycle bin. You can also press Shift+Del to bypass the recycle bin and permanently delete the file.

Using a command-line interface

There aren't many options for creating files from the command line. You can create a simple text file by redirecting output from a command. Here is an example:

> echo hello > myfile.txt

One command you may not be familiar with is creatfil.exe from the Resource Kit. With it you can create files of arbitrary length. This is useful only if you need to create some files to test with or to test low disk space scenarios. The following command creates a 10 MB file named foobar.txt:

> creatfil foobar.txt 10240

To delete a file use the del command:

> del c:\scripts\foobar.vbs

If you want to delete a file on a remote system, you can use the psexec command (from Sysinternals):

> psexec \\<ComputerName> cmd.exe /c del c:\scripts\foobar.vbs

To provide alternate credentials with psexec use the /u and /p options to specify a username and password respectively.

Using VBScript

See Chapter 1 for examples of creating and appending to files using VBScript.

' This code deletes a file ' ------ SCRIPT CONFIGURATION ------ strFilePath = "<FilePath>" ' e.g. "d:\scripts\test.txt" ' ------ END CONFIGURATION --------- set objFSO = CreateObject("Scripting.FileSystemObject") objFSO.DeleteFile(strFilePath) WScript.Echo "Successfully deleted file" ' This code deletes a file using WMI ' ------ SCRIPT CONFIGURATION ------ strComputer = "." strFilePath = "<FilePath>" ' e.g. "d:\scripts\test.txt" ' ------ END CONFIGURATION --------- set objFile = GetObject("winmgmts:\\"& strComputer & _                         "\root\cimv2:CIM_Datafile.Name='" & strFilePath & "'") objFile.Delete WScript.Echo "Successfully deleted file"



Windows XP Cookbook
Windows XP Cookbook (Cookbooks)
ISBN: 0596007256
EAN: 2147483647
Year: 2006
Pages: 408

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net