来自For Each的VBS多维数组

时间:2017-03-24 22:01:42

标签: multidimensional-array vbscript

透视:此脚本将在用户登录和命令上运行,并在桌面上显示快捷方式。应用程序启动的顺序势在必行。在整个脚本中,我需要完整路径和程序名称。

问题:每个程序路径都是数组中的值。我试图通过“\”拆分每个程序路径并获取上限以获取程序名称。然后Redim保留原始数组并在第二维上添加程序。阅读了好几个小时后,我掌握了我只能改变最后一个维度,但我无法弄清楚如何不出错。此Creating a Multidimensional, Associative Array in VBScript并未尝试从For Each拆分中重新保留。

Set objFso = CreateObject("Scripting.FileSystemObject")

'---Create Program Variables
strProgram1 = "%SystemRoot%\notepad.exe" 
strProgram2 = "C:\Program Files\Microsoft Office\root\Office16\OUTLOOK.EXE" 
strProgram3 = "C:\Program Files\Microsoft Office\root\Office16\ONENOTE.EXE" 
strProgram4 = "C:\Program Files (x86)\Internet Explorer\iexplore.exe" & " https://www.google.com" 'IE with URL

'---Add Program Path Variables to an Array
ReDim strProgramList(3) 
strProgramList = Array(strProgram1,strProgram2,strProgram3,strProgram4)

strProgramNameList = Array()
strProgramRestartList = Array()
boolNeedsRestart = false

'---Iterating using For each loop to get program name. 
ReDim Preserve strProgramList(3, 1)
For Each strProgramPath In strProgramList
        strPathComponents = Split(strProgramPath, "\")
        strProgramName = strPathComponents(Ubound(strPathComponents))
        strProgramList(0, LBound(strProgramList) + 1) = strProgramName

Next

MsgBox strProgramList(0,0) & vbNewLine & strProgramList(1,0) & vbNewLine & strProgramList(2,0)  & vbNewLine & strProgramList(3,0) & vbNewLine & strProgramList(0,1) & vbNewLine & strProgramList(1,1) & vbNewLine & strProgramList(2,1) & vbNewLine & strProgramList(3,1)

1 个答案:

答案 0 :(得分:1)

如何使用FileSystemObject解析/构建pathes以及如何使用二维arrays

Option Explicit

Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
Dim a    : a        = Split("A:\B\CC.EXE A:\CC\DD.CMD C:\You\Got\It.pl")
ReDim b(2, UBound(a))
Dim i
For i = 0 To UBound(a)
   b(0, i) = a(i)
   b(1, i) = goFS.GetParentFolderName(a(i))
   b(2, i) = goFS.GetFileName(a(i))
Next
ReDim Preserve b(2, UBound(b, 2) + 1)
b(0, UBound(b, 2)) = "P:\i\pa\po.py"
b(1, UBound(b, 2)) = goFS.GetParentFolderName(b(0, UBound(b, 2)))
b(2, UBound(b, 2)) = goFS.GetFileName(b(0, UBound(b, 2)))
For i = 0 To UBound(b, 2)
   WScript.Echo b(0, i), "=", b(1, i), "+", b(2, i), "=>", goFS.BuildPath(b(1, i), b(2, i))
Next

输出:

cscript twodim.vbs
A:\B\CC.EXE = A:\B + CC.EXE => A:\B\CC.EXE
A:\CC\DD.CMD = A:\CC + DD.CMD => A:\CC\DD.CMD
C:\You\Got\It.pl = C:\You\Got + It.pl => C:\You\Got\It.pl
P:\i\pa\po.py = P:\i\pa + po.py => P:\i\pa\po.py