3

In the command line you can output the current directory using echo %CD% like this this:

enter image description here

The Windows Scripting Host provides the ExpandEnvironmentalStrings method which can be used like this:

Dim objWshShell : Set objWshShell = CreateObject("Wscript.Shell")
MsgBox objWshShell.ExpandEnvironmentStrings("%WINDIR%")

enter image description here

However, it doesn't work with %CD%. It just returns the same value, %CD%:

Dim objWshShell : Set objWshShell = CreateObject("Wscript.Shell")
MsgBox objWshShell.ExpandEnvironmentStrings("%CD%")

enter image description here

Why doesn't this work? I know there are other ways to get the current directory; this is just a curiousity.

rory.ap
  • 34,009
  • 10
  • 83
  • 174

1 Answers1

9

The variable %CD% is a CMD-builtin automatic variable, not an environment variable like %PATH% or %USERNAME%. It can only be used within CMD, e.g.

cmd /c echo %CD%

Same goes for the variables %TIME%, %DATE%, and %ERRORLEVEL%.

If you want the current working directory in VBScript you need to use the CurrentDirectory property of the WshShell object

Set sh = CreateObject("WScript.Shell")
WScript.Echo sh.CurrentDirectory

or expand the path of the directory .:

Set fso = CreateObject("Scripting.FileSystemObject")
WScript.Echo fso.GetAbsolutePathName(".")
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328