2016-12-16 87 views
3

在命令行可以輸出使用echo %CD%這樣這個當前目​​錄:爲什麼WScript.Shell.ExpandEnvironmentStrings不能使用%CD%?

enter image description here

Windows腳本宿主提供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

爲什麼不工作的呢?我知道還有其他方法來獲取當前目錄;這只是一個好奇心。

回答

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(".")