我有這個簡單的 cmdlet 可以正確地將檔案和檔案夾復制到第二個目錄:
Copy-Item -Path 'G:\xyz\Test\A' -Recurse -Destination 'G:\xyz\Test\B\'
但是,我無法將其調整為僅復制其檔案夾內每個檔案夾中的最新檔案(即也復制檔案夾結構)。我已經寫了以下內容,但這不會復制檔案夾名稱,也不會遍歷子檔案夾的所有層次結構。
Get-ChildItem -Path 'G:\xyz\Test\A' -Directory | ForEach-Object {
Get-ChildItem -Path 'G:\xyz\Test\A' -File -Recurse |
Sort-Object LastWriteTime | Select-Object -Last 1 |
Copy-Item -Destination 'G:\xyz\Test\B\'
}
有人可以找出我的錯誤!
uj5u.com熱心網友回復:
首先收集目錄然后遍歷它們以檢索檔案的稍微不同的方法。
If ( -not (Test-Path -Path "G:\Test\B")) {
$Null = New-Item -ItemType "Directory" "G:\Test\B"
}
Get-ChildItem -Path 'G:\Test\A' -Directory -Recurse |
#Sort to insure dirs are created shortest to longest
Sort-Object FullName |
ForEach-Object {
$DestPath = $($_.FullName).Replace("`\Test`\A","`\Test\`B")
If ( -not (Test-Path -Path "$DestPath")) {
$Null = New-Item -ItemType "Directory" "$DestPath"
}
Get-ChildItem -Path "$($_.FullName)" -File |
Sort-Object LastWriteTime |
Select-Object -Last 1 |
Copy-Item -Destination "$DestPath"
}
uj5u.com熱心網友回復:
第一個錯誤是您沒有將當前目錄從外部Get-ChildItem傳遞到內部。內部的當前總是在同一個子目錄上回圈。
此外,當您在管道中復制單個檔案時Get-ChildItem,您必須自己構建目標路徑,以保持相對源目錄結構:
$source = 'G:\xyz\Test\A'
$destination = 'G:\xyz\Test\B\'
# Set base directory for outer Get-ChildItem and Resolve-Path -Relative
Push-Location $source
try {
Get-ChildItem -Directory | ForEach-Object {
Get-ChildItem -Path $_.Fullname -File -Recurse |
Sort-Object LastWriteTime | Select-Object -Last 1 |
ForEach-Object {
# Make the current file path relative to $source
$relativePath = Resolve-Path $_.Fullname -Relative
# Build up the full destination file path
$destinationFullPath = Join-Path $destination $relativePath
# Create destination directory if not already exists (-force)
$null = New-Item (Split-Path $destinationFullPath -Parent) -ItemType Directory -Force
# Copy the current file
Copy-Item -Path $_.Fullname -Destination $destinationFullPath
}
}
}
finally {
Pop-Location # Restore the current directory
}
Resolve-Path -Relative使給定路徑相對于當前目錄。為了獲取相對于源目錄的路徑,我們將當前目錄設定為源目錄路徑,使用Push-Location.- 和塊確保即使在腳本終止錯誤(例外)的情況下也能恢復當前目錄
try。finally
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/524039.html
標籤:电源外壳递归
上一篇:SQLite遞回函式
