Export (0) Print
Expand All
3 out of 4 rated this helpful - Rate this topic

Retrieving and Changing a Scripts Current Working Directory

Microsoft® Windows® 2000 Scripting Guide

The working directory for a script is initially set to the directory from which the script is started. This is not necessarily the directory where the script file is located. If you are working in the C:\Temp directory, for example, and you type c:\scripts\report.vbs to run the Report.vbs script, the working directory is C:\Temp, even though the actual script file, Report.vbs, is located in the C:\Scripts directory.

The WshShell object provides the CurrentDirectory property to allow your scripts to determine or modify their current working directory.

There are a number of reasons why you might need to know and possibly change the current working directory of a script. For example:

  • You want your script to create a log file in the same folder as the script.

  • You want to determine whether the script has been run locally or from across the network. (The current working directory will start with two backslashes [\\] instead of a drive letter such as C if it has been run from across the network.)

To retrieve the current directory for a script, create an instance of the WshShell object, and then echo the value of the CurrentDirectory property. To configure the working directory, simply assign a new value to this property.

The script in Listing 3.31 uses the CurrentDirectory property to both retrieve and set a scripts working directory. If the specified working directory does not exist, the script will fail.

Listing 3.31 Setting and Retrieving a Scripts Current Working Directory

  
1
2
3
4
5
6
7
8
9


Set objShell = WScript.CreateObject("WScript.Shell")

Wscript.Echo "Initial Working Directory:"
Wscript.Echo objShell.CurrentDirectory

objShell.CurrentDirectory = "C:\"

Wscript.Echo "Working Directory After Change:"
Wscript.Echo objShell.CurrentDirectory

If the preceding script is started from the folder C:\Temp, the following output will appear in the command window:



Initial Working Directory:
C:\Temp
Working Directory After Change:
C:\

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.