2017-03-24 50 views
0

透視圖:此腳本將在用戶登錄和命令上運行,並在桌面上使用快捷方式。申請開始的順序勢在必行。在整個腳本中,我需要完整路徑和程序名稱。來自For Each的VBS多維數組

問題:每個程序路徑都是數組中的一個值。我試圖通過「\」拆分每個程序路徑,並獲取程序名的上限。然後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) 
+0

的可能的複製[創建多維, VBScript中的關聯數組](// stackoverflow.com/q/4588469) – Lankymart

回答

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 
+0

那麼解釋代碼,而不是我們更少的凡人呢? – Lankymart

+0

霍納,我想你已經正確地理解了我的意圖。 我最初用strProgramList替換了你的文件路徑,將它設置爲「a」。我收到了「類型不匹配」的錯誤。然後我將它改爲strProgramList(1),看看我是否知道發生了什麼。這次你的代碼運行,顯然只有第一個程序,但是它在空間上分裂。我試着將它改爲這個Dim a:a = Split(strProgramList(1),「\」)但沒有奏效。 謝謝 – user2847926

+0

@ user2847926這不是正確理解你的意圖的情況,而是提供足夠詳細的答案來幫助其他可能有類似問題的人。無論如何,這個問題是明顯的重複,我們不是在這裏解決你的代碼的細微差別。 – Lankymart