使用以下代码,我遇到了可怕的运行时:
Option Explicit
Dim ShellEnvironment: Set ShellEnvironment=CreateObject ("WScript.Shell").Environment ("USER")
Dim Name: Name="MyVar"
Dim NewVal: NewVal="This is my value"
Services.StartTransaction "SetEnv"
ShellEnvironment (Name)=NewVal
Services.EndTransaction ("SetEnv")
请注意,只有Services。* stuff是特定于QTP的。这两个语句生成以下运行结果条目,指示环境变量赋值的运行时:
Transaction "SetEnv" ended with "Pass" status (Total Duration: 12.1970 sec).
这是一台非常快的机器。当然这是一个不可接受的长运行时间。
根据Environment.SetEnvironmentVariable takes a long time to set a variable at User or Machine level,这是因为所有顶级窗口都会以1秒超时通知。我不确定这是否是C#特定的。嗯,显然不是。但我不知道如何在VBScript下控制这个通知/超时过程。
总的来说,问题是:
如何在VBScript中设置USER环境变量而不会产生可怕的运行时?
答案 0 :(得分:0)
似乎没有办法控制ShellEnvironment用于通知广播的超时。
所以我决定建立一个解决方法。
我称这个剧本为:
Option Explicit
Dim Name
Dim NewVal
If WScript.Arguments.Count <> 2 then
WScript.Echo "setUSEREnv.vbs: Pass name and value of USER environment variable to set on the command line"
WScript.Quit (1)
End If
Name=CStr (WScript.Arguments.Item (0))
NewVal=CStr (WScript.Arguments.Item (1))
Dim ShellEnvironment: Set ShellEnvironment=CreateObject ("WScript.Shell").Environment ("USER")
If ShellEnvironment (Name) <> NewVal then
ShellEnvironment (Name)=NewVal
WScript.Echo "Setting USER env var '" & Name & "'..."
WScript.Echo "USER env var '" & Name & "' set to '" & NewVal & "'"
else
WScript.Echo "USER env var '" & Name & "' already is '" & NewVal & "'"
End If
使用Run
来自我的setenv功能代码:
Dim ShellEnvironment: Set ShellEnvironment=CreateObject ("WScript.Shell").Environment ("USER")
Dim Name: Name=EnvVarName
If ShellEnvironment (Name) <> NewVal Then
Dim Shell: Set Shell=CreateObject ("WScript.Shell")
Shell.Run "cscript.exe ""c:\mydir\setUSERENV.vbs"" " & Name & " " & CStr (NewVal), 0, false
End If
对于每个env var写访问,这仍然会让我感到很沮丧,但至少主脚本一直在运行,所以我不必等待。