我使用 get-childitem 從目錄結構中獲取檔案。
Get-ChildItem $path -Recurse -include *.jpg,*.png | select-object Directory, BaseName, Extension
我得到一組具有屬性 Directory、BaseName、Extension 的物件。
像:
Directory BaseName Extension
C:\dir1\dir2\dir3\dir4 file txt
我不想將目錄結構分解為同一個陣列中的多個屬性 - 每個子目錄級別都是它自己的屬性。
最終結果屬性應該是(我可以在腳本的前面洗掉 c:\):
dir1 dir2 dir3 dir4 Basename Extension
dir1 dir2 dir3 dir4 file txt
我曾經將其匯出到 csv 并使用分隔符將其匯入另一個陣列,而不是重建原始陣列,但我認為必須有更簡單的方法!
uj5u.com熱心網友回復:
這是一種可能的方法:
$path = 'C:\test'
$maxDepth = 0
Set-Location $path # Set base path for Resolve-Path -Relative
# Get all files and splits their directory paths
$tempResult = Get-ChildItem $path -Recurse -include *.jpg,*.png | ForEach-Object {
# Make directory path relative to $path
$relPath = Resolve-Path $_.Directory -Relative
# Create an array of directory path components, skipping the first '.' directory
$dirNames = $relPath -replace '^\.\\' -split '\\|/'
# Remember maximum directory depth
$maxDepth = [Math]::Max( $dirNames.Count, $maxDepth )
# Implicit output that PowerShell adds to $tempResult
[PSCustomObject]@{
dirNames = $dirNames
fileInfo = $_ | Select-Object BaseName, Extension
}
}
# Process $tempResult to add directory properties and file name properties
$finalResult = $tempResult.ForEach{
$outProps = [ordered] @{}
# Add directory properties
for( $i = 0; $i -lt $maxDepth; $i ) {
$outProps[ "Dir$i" ] = if( $i -lt $_.dirNames.Count ) { $_.dirNames[ $i ] } else { $null }
}
# Add all fileInfo properties
$_.fileInfo.PSObject.Properties.ForEach{ $outProps[ $_.Name ] = $_.Value }
# Implicit output that PowerShell adds to $finalResult
[PSCustomObject] $outProps
}
$finalResult # Output to console
這是在兩遍中完成的,以確保所有輸出元素具有相同數量的目錄屬性:
- 遍歷所有檔案并拆分它們的目錄路徑。確定最大目錄深度(目錄屬性的數量)。
- 迭代中間結果以創建由目錄屬性和檔案名屬性組成的所需物件。這是通過首先將屬性添加到有序哈希表,然后將該哈希表轉換為
PSCustomObject. 這比使用Add-Member.
測驗輸入:
C:\test
\subdir1
file1.png
file2.jpg
\subdir2
\subdir3
file3.jpg
輸出:
Dir0 Dir1 BaseName Extension
---- ---- -------- ---------
subdir1 file1 .png
subdir1 file2 .jpg
subdir2 subdir3 file3 .jpg
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/475547.html
標籤:电源外壳
