Can I Change the Current Directory When Running a Script?

ScriptingGuy1

Hey, Scripting Guy! Question

Hey, Scripting Guy! Can I change the current directory while my script is running?

— KO, Kalispell, MT

SpacerHey, Scripting Guy! AnswerScript Center

Hey, KO. Yes, you can change the current directory while a script is running, provided you are running Windows Script Host 5.6, that is. To change the current directory, all you have to do is create an instance of the Wscript.Shell object, and then set the value of the CurrentDirectory property to the desired directory. For example, this little two-line script changes the current directory to C:\Temp:

Set objShell = CreateObject("WScript.Shell")
objShell.CurrentDirectory = "C:\Temp"

To verify that this works, copy this script, save it to some folder (doesn’t matter which one, as long as it isn’t C:\Temp) and then run it. You should see two items get echoed to the screen: the name of the folder where you started the script from, and then the new current directory, C:\Temp:

Set objShell = CreateObject("WScript.Shell")
WScript.Echo objShell.CurrentDirectory
objShell.CurrentDirectory = "C:\Temp"
WScript.Echo objShell.CurrentDirectory

If the folder C:\Temp doesn’t exist, you’ll get a file not found error.

Incidentally, as implied above the current directory for a script isn’t necessarily the folder where the script lives, it’s the folder you were in when you started the script. Suppose the script is in C:\Scripts. You open a command prompt window, change to the Windows directory, and then type this:

cscript c:\scripts\my_script.vbs

In that case, the current directory will be C:\Windows, not C:\Scripts.

For more information about the CurrentDirectory property, see the Windows Script Host documentation on MSDN.

0 comments

Discussion is closed.

Feedback usabilla icon