数组循环代码中每个项目的 VBScript

VBScript For Each Item in the Array Loop Code

所以我将这段代码放在一起并完成了工作,但我逐渐意识到,这可以通过 For Each 循环和数组进一步优化。该代码从命令行运行 HTA 应用程序并采用两个已预设的参数。我想做的是最大限度地减少代码量,但我一直遇到一些问题,所以我唯一需要编辑的是数组值并保持其他所有内容几乎是静态的。

我试图完成的示例(我知道语法不正确只是想画一幅图):

Dim objShell, command
Set objShell = WScript.CreateObject ("WScript.Shell") 
command = "cmd /c wmic process where name=""mshta.exe"" call terminate"
objShell.Run command, 0, True 

Dim preMSI
preMSI = "MSI_"

Dim postMSI
postMSI = "_5"

Dim startPKG
startPKG = "Build"

Array(4O, AT, LQ)

ForEach ArrayValue (

 'Prep Name Change
 objShell.run "cmd.exe /C REN D:\"&startPKG&" "&firstArraryValue&"", 0, True
 'Launch and Execute Package Build
 objShell.run "D:\BUILDER.hta """&preMSI+Var1+postMSI&""" ""D:\"&Var1&""" ", 0, True
 objShell.Run command, 0, True 
'Rename the DIR from the first value to the second and so forth as it iterates
 objShell.run "cmd.exe /C REN D:\"&firstArraryValue&" "&secondArraryValue&"", 0, True

)

我的实际代码:

Dim objShell, command
Set objShell = WScript.CreateObject ("WScript.Shell") 
command = "cmd /c wmic process where name=""mshta.exe"" call terminate"
objShell.Run command, 0, True 


Dim preMSI
preMSI = "MSI_"

Dim postMSI
postMSI = "_5"

Dim startPKG
startPKG = "Build"

 Dim Var1
 Var1 = "4O"

 'Prep Name Change
 objShell.run "cmd.exe /C REN D:\"&startPKG&" "&Var1&"", 0, True
 'Launch and Execute Package Build
 objShell.run "D:\BUILDER.hta """&preMSI+Var1+postMSI&""" ""D:\"&Var1&""" ", 0, True
 objShell.Run command, 0, True 

 Dim Var2
 Var2 = "AT"

 'Prep Name Change
 objShell.run "cmd.exe /C REN D:\"&Var1&" "&Var2&"", 0, True
 'Launch and Execute Package Build
 objShell.run "D:\BUILDER.hta """&preMSI+Var2+postMSI&""" ""D:\"&Var2&""" ", 0, True
 objShell.Run command, 0, True 

 Dim Var3
 Var3 = "LQ"

 'Prep Name Change
 objShell.run "cmd.exe /C REN D:\"&Var2&" "&Var3&"", 0, True
 'Launch and Execute Package Build
 objShell.run "D:\BUILDER.hta """&preMSI+Var3+postMSI&""" ""D:\"&Var3&""" ", 0, True
 objShell.Run command, 0, True 

据我所知,你想要做的很接近这个(显然未经测试)。

我已经删除了所有 "start CMD.EXE to rename a folder" 位,还有更好的方法可以做到这一点。我还使用了 VBScript 的 WMI 本机接口。

Option Explicit

Dim Shell, FSO, Locator, WMI, process, folder, item

Set Shell = CreateObject("WScript.Shell") 
Set FSO = CreateObject("Scripting.FileSystemObject")
Set Locator = CreateObject("WbemScripting.SWbemLocator")
Set WMI = Locator.ConnectServer(".", "ROOT\CIMV2")

' terminate all existing mstha processes
For Each process In WMI.ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'mshta.exe'")
    process.terminate
Next

Set folder = FSO.GetFolder("D:\Build")

For Each item In Array("4O", "AT", "LQ")
    folder.Name = item
    Shell.run "D:\BUILDER.hta ""MSI_" & item & "_5"" """ & folder.Path & """", 0, True
Next

folder.Name = "Build"

如果列表 "4O", "AT", "LQ" 是可配置的,请在调用脚本时将其作为命令行参数传递:

cscript /nologo your.vbs "4O,AT,LQ"

并在脚本中

For Each item In Split(WScript.Arguments.Unnamed(0), ",")
    ' ...
Next