Recipe 4.1. Creating and Deleting a FileProblemYou want to create or delete a file. SolutionUsing a graphical user interface
Using a command-line interfaceThere 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 server, you can use a psexec.exe command like this: > psexec \\<ServerName> 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 VBScriptSee 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" |