为什么WScript.Shell.ExpandEnvironmentStrings不能使用%CD%?

时间:2016-12-16 19:26:07

标签: vbscript environment-variables wsh

在命令行中,您可以使用echo %CD%输出当前目录,如下所示:

enter image description here

Windows Scripting Host提供the ExpandEnvironmentalStrings method,可以像这样使用:

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

enter image description here

但是,它不适用于%CD%。它只返回相同的值%CD%

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

enter image description here

为什么这不起作用?我知道还有其他方法可以获取当前目录;这只是一种好奇心。

1 个答案:

答案 0 :(得分:8)

变量%CD%是CMD内置的自动变量,而不是像%PATH%%USERNAME%这样的环境变量。它只能在CMD中使用,例如

cmd /c echo %CD%

变量%TIME%%DATE%%ERRORLEVEL%也是如此。

如果您想要VBScript中的当前工作目录,则需要使用WshShell对象的CurrentDirectory属性

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

expand the path

Set fso = CreateObject("Scripting.FileSystemObject")
WScript.Echo fso.GetAbsolutePathName(".")