是否可以在Windows Scripting Host(WSH)VBS脚本中读取系统环境变量?
(我正在使用Windows Scripting Host编写VBScript以获取Cruise Control的任务,并希望获取项目构建URL。)
答案 0 :(得分:25)
以下是一个示例(取自here):
Set oShell = CreateObject( "WScript.Shell" )
user=oShell.ExpandEnvironmentStrings("%UserName%")
comp=oShell.ExpandEnvironmentStrings("%ComputerName%")
WScript.Echo user & " " & comp
答案 1 :(得分:7)
来自here ...
Set WshShell = WScript.CreateObject("WScript.Shell")
Set WshProccessEnv = WshShell.Environment("Process")
Set WshSysEnv = WshShell.Environment("System")
Wscript.Echo WshSysEnv("NUMBER_OF_PROCESSORS")
Wscript.Echo WshProccessEnv("Path")
此外,更多detail on TechNet。
答案 2 :(得分:5)
现有答案都很有帮助,但让我尝试务实的摘要:
通常,您希望 当前流程定义环境变量:
CreateObject("WScript.Shell").ExpandEnvironmentStrings("%TEMP%")
这相当于(注意变量名称周围没有%
):
CreateObject("WScript.Shell").Environment("Process").Item("TEMP")
警告:不要忽略("Process)
部分:如果这样做,您将获得系统范围' s变量的定义;见下文。
.ExpandEnvironmentStrings
在概念上更简单,更灵活:它可以使用 embedded (%
扩展任意字符串 - 附带的)环境变量参考; e.g:
CreateObject("WScript.Shell").ExpandEnvironmentStrings("My name is %USERNAME%")
在极少数情况下,您可能必须从特定范围访问环境变量定义 (当前流程除外)。
sScope = "System" ' May be: "Process", "User", "Volatile", "System"
CreateObject("WScript.Shell").Environment(sScope).Item("TEMP")
注意:如上所述,省略scope参数默认为System
范围。
警告:以这种方式访问值不会展开:环境变量值可以嵌套:它们可以引用其他环境变量
在上面的示例中,返回值为%SystemRoot%\TEMP
,其中包含未展开对%SystemRoot%
的引用。
要展开结果,请将其传递给.ExpandEnvironmentStrings()
,如上所示。
答案 3 :(得分:4)
Set WshShell = CreateObject("WScript.Shell")
Set WshEnv = WshShell.Environment
WScript.Echo "WINDIR=" & WshEnv.Item("WINDIR") & vbCrLf & vbCrLf
Set WshShell = CreateObject("WScript.Shell")
WScript.Echo "Environment System:" & vbCrLf & _
"..............................................."
For Each IEnv In WshShell.Environment("System")
WScript.Echo IEnv
Next
WScript.Echo vbCrLf & "Environment User:" & vbCrLf & _
"..............................................."
For Each IEnv In WshShell.Environment("User")
WScript.Echo IEnv
Next
WScript.Echo vbCrLf & "Environment Volatile:" & vbCrLf & _
"..............................................."
For Each IEnv In WshShell.Environment("Volatile")
WScript.Echo IEnv
Next
WScript.Echo vbCrLf & "Environment Process:" & vbCrLf & _
"..............................................."
For Each IEnv In WshShell.Environment("Process")
WScript.Echo IEnv
Next
答案 4 :(得分:-1)
这对我有用:
Dim objNetwork
Set objNetwork = CreateObject("WScript.Network")
MsgBox objNetwork.UserName
或来自shell:
Set wshShell = WScript.CreateObject( "WScript.Shell" )
strUserName = wshShell.ExpandEnvironmentStrings( "%USERNAME%" )
或来自环境变量(它应该可以工作,但是当我测试它是错误的!):
Set WshShell = CreateObject("WScript.Shell")
Set WshEnv = WshShell.Environment
MsgBox "USERNAME=" & WshEnv.Item("USERNAME")