
我正在嘗試將文件從一個資料夾複製到另一個資料夾。我的文件中有某種隨機前綴。但我有 csv 檔案中檔案名稱的最後一部分。
New-Item -ItemType Directory -Path "\\newpart\xxx\$((Get-Date).ToString('dd-MM-yyyy'))_test" -Force
Import-Csv '\\csvpath\xxx\file.csv' |
ForEach {Copy-Item -path \\oldpath\xxx\* -filter $($_.Fil) "\\newpath\xxx\$((Get-Date).ToString("dd-MM-yyyy"))_text" }
我的文件看起來是這樣的:
{001588D8-5FF0-409C-9BF7-A3AE6D0B26CF} - AppImage20160520115646078.jpg
CSV 檔案只有檔案名稱的這一部分:
AppImage20160520115646078.jpg
答案1
在 中使用*
通配符-filter "*$($_.Fil)"
。
另一方面,Copy-Item
文件說它的-Path
參數不接受通配符。
$newTarget = "\\newpart\xxx\$((Get-Date).ToString('dd-MM-yyyy'))_test"
New-Item -ItemType Directory -Path "$newTarget" -Force
Import-Csv '\\csvpath\xxx\file.csv' |
ForEach {
Get-ChildItem "\\oldpath\xxx\*$($_.Fil)" -File -ErrorAction SilentlyContinue |
ForEach { Copy-Item -path $PSItem.FullName -Destination "$newTarget" }
}
或(也許更好)
$newTarget = "\\newpart\xxx\$((Get-Date).ToString('dd-MM-yyyy'))_test"
New-Item -ItemType Directory -Path "$newTarget" -Force
Import-Csv '\\csvpath\xxx\file.csv' |
ForEach {
Get-ChildItem "\\oldpath\xxx\*$($_.Fil)" -File -ErrorAction SilentlyContinue |
Copy-Item -Destination "$newTarget"
}
答案2
您應該能夠在腳本檔案中執行此操作,例如 Copy-FilesFromCsv.ps1:
#mkdir files
#touch "files\{001588D8-5FF0-409C-9BF7-A3AE6D0B26CF} - AppImage20160520115646078.jpg"
$csvPath = "$PSScriptRoot\" # "\\csvpath\xxx\"
$sourceFolder = "$PSScriptRoot\files\"
$newFolder = "$PSScriptRoot\files\$((Get-Date).ToString('dd-MM-yyyy'))_test"
New-Item -WhatIf -ItemType Directory $newFolder -Force
ForEach ($file in $(Import-Csv "${csvPath}file.csv"))
{
Copy-Item -WhatIf -Path "$sourceFolder*$($file.Fil)" -Destination $newFolder
}