PowerShell:陣列的陣列

PowerShell:陣列的陣列

我有具有以下結構的文件:

c:\root\dir1\001 (BRP-01 Some) Text.tif
c:\root\dir2\002 (BRP-01 Some Different) Text.tif
c:\root\dir3\001 (BRP-01 Some) Text.tif
...

最終,我想根據文件名前三位數字的連續範圍來提取文件。我最初的方法是嘗試Array of Arrays儲存目錄資訊和文件資訊......然後將隨後採取行動來提取和評估前三個數字並進一步操作。然而,我在 PS 中使用陣列的經驗有限,並且在儲存資料、存取資料或兩者兼而有之時遇到了問題。

如果您能幫助糾正我的文法,我將不勝感激。另外,如果我可能考慮更好的方法,我願意接受替代方法。

PS C:\root\> Get-ChildItem *.tif -recurse | foreach-object {$a=$_.DirectoryName; $b=$_.Name; $c+=@(@($a,$b)); foreach ($i in $c) {echo $i[0]}
# I realize something "breaks" after $c+= ... but I am unsure what. The script runs but I cannot access the respective fields as expected or the data isn't being populated as expected.

一旦我有了正確的語法,我希望數組返回如下所示的內容:

$i[0]: 
       c:\root\dir1\
       c:\root\dir2\
       c:\root\dir3\
$i[1]: 
       001 (BRP-01 Some) Text.tif
       002 (BRP-01 Some Different) Text.tif
       001 (BRP-01 Some) Text.tif
$i[0][1]: c:\root\dir1\

Array of Arrays我非常有信心,一旦我能夠牢牢掌握數據的建構方式以及從中調用數據的方式,我就可以操縱數據。

謝謝!

答案1

我認為你把這件事過於複雜化了。運行命令後,您不需要任何進一步的「資料格式化」Get-ChildItem。您只需要Group-Object根據檔案名稱的前 3 個字元來輸出,如下所示:

$AllItemsGrouped = Get-ChildItem *.tif -recurse | Group-Object { $_.Name.Substring(0,3) }

這將返回您的對象,分組為各自的前綴,而不會丟失任何資訊:

PS C:\Install\testdir500> gci | group-object { $_.Name.substring(0,3) }

Count Name                      Group
----- ----                      -----
    3 001                       {001test - Kopie (2).txt, 001test - Kopie.txt, 001test.txt}
    2 002                       {002test - Kopie.txt, 002test.txt}
    1 003                       {003test - Kopie - Kopie.txt}

例如,如果展開一個群組,則內容如下所示:

PS C:\Install\testdir500> gci | group-object { $_.Name.substring(0,3) } | select -expand Group -first 1


    Verzeichnis: C:\Install\testdir500


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       30.11.2020     09:55              0 001test - Kopie (2).txt
-a----       30.11.2020     09:55              0 001test - Kopie.txt
-a----       30.11.2020     09:55              0 001test.txt

然後您可以透過不同的方式存取它,例如:

foreach ($Group in $AllItemsGrouped) {

    $CurrentGroup = $Group.Group
    Do-Something -With $CurrentGroup

}

相關內容