在VBS中使用环境变量值时遇到问题

时间:2014-12-30 18:37:20

标签: xml vbscript environment-variables

我是VBScript的新手并编写了一个可以修改XML文件的小脚本;但我在将计算机名称放入XML时遇到了麻烦。

我使用以下行从HOST环境变量中获取了计算机名称:

 Set wshShell = CreateObject( "WScript.Shell" )
 WScript.Echo wshShell.ExpandEnvironmentStrings( "HOST=%HOST%" )

但是,现在我不清楚如何将它放在XML中的几条路径中 - 这意味着我希望计算机名称在您看到%HOST%下面的任何地方:

sWebcastFlash = "%HOST%:port/webcast/"
sWebcastInfra = "%HOST%/webcast/"
sWebcastTelephone = "%HOST%:port/telephone/"
上述字符串中的

%HOST%没有像我希望的那样扩展到HOST环境变量的值。我错过了什么?

这是我的完整脚本:

Set wshShell = CreateObject( "WScript.Shell" )
WScript.Echo wshShell.ExpandEnvironmentStrings( "HOST=%HOST%" )
'wshShell = Nothing


sWebcastFlash = "%HOST%:port/webcast/"
sWebcastInfra = "%HOST%/webcast/"
sWebcastTelephone = "%HOST%:port/telephone/"

'Create XMLDoc object
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.load "D:\Configuration\developer\developer-definitions.xml"

Set nWebcastFlash = xmlDoc.selectSingleNode("//clusters/cluster/servers/server/webcast-fms-url-for-flash")
Set nWebcastInfra = xmlDoc.selectSingleNode("//clusters/cluster/servers/server/webcast-fms-url-for-infra")
Set nWebcastTelephone = xmlDoc.selectSingleNode("//clusters/cluster/servers/server/webcast-fms-telephone-preview-url")
Set nWebcamUrl = xmlDoc.selectsinglenode ("//clusters/cluster/servers/server/webcam-self-test-url")
Set nHostName = xmlDoc.selectsinglenode ("//clusters/cluster/servers/server/host-name")
Set nHostAddress = xmlDoc.selectsinglenode ("//clusters/cluster/servers/server/host-address")
Set nAudUrl = xmlDoc.selectsinglenode ("//media-definitions/media-servers/on-demand-media-url/url-list/url/aud-url")
Set nFlashUrl = xmlDoc.selectsinglenode ("//flash-server-chat-list-url/flash-server-url")
Set nWebcamTest = xmlDoc.selectsinglenode ("//flash-server-webcam-self-url/webcam-self-test")

'Set the text node with the new value
nWebcastFlash.text = sWebcastFlash
nWebcastInfra.text = sWebcastInfra
nWebcastTelephone.text = sWebcastTelephone
'Save the xml document with the new settings.
strResult = xmldoc.save("D:\out.xml")

1 个答案:

答案 0 :(得分:3)

您只需将展开的HOST环境变量分配给局部变量,并将其添加到您要使用它的字符串中:

Set wshShell = CreateObject( "WScript.Shell" )
host = wshShell.ExpandEnvironmentStrings( "%HOST%" )
wshShell = Nothing


sWebcastFlash = host & ":port/webcast/"
sWebcastInfra = host & "/webcast/"
sWebcastTelephone = host & ":port/telephone/"

修改

@Tomalak在评论中提出了一个很好的观点。为了完整起见,您还可以通过调用ExpandEnvironmentStrings来为要使用HOST环境变量值的每个字符串完成此操作:

Set wshShell = CreateObject( "WScript.Shell" )

sWebcastFlash = wshShell.ExpandEnvironmentStrings( "%HOST%:port/webcast/" )
sWebcastInfra = wshShell.ExpandEnvironmentStrings( "%HOST%/webcast/" )
sWebcastTelephone = wshShell.ExpandEnvironmentStrings( "%HOST%:port/telephone/" )

wshShell = Nothing

正如@Tomalak进一步指出的那样,这涉及更多的代码:在我看来,它是不必要的重复,但TMTOWTDI。