
我在 Windows 中有一個 CSV 檔案(實際上是用分號分隔的),其中包含列標題資訊。其中一列包含部分檔案名稱;它是一個沒有路徑或擴展名的檔案名稱。我一直在嘗試建立一個 PowerShell 或 Robocopy 腳本來讀取該列並將該列中列出的所有檔案從共用資料夾複製到本機資料夾,但我無法讓它運作。
這就是輸入檔的樣子
COL1;COL2;COL3;COL4;COL5
COL2
包含不含副檔名的檔案名稱。
所有需要的檔案都位於檔案伺服器上的某個位置\\server\share\folder\
,或者\\server\share\folder\subfolder
– 我不知道確切的來源目錄。
我可以建立一個 PowerShell 或 Robocopy 腳本來讀取COL2
、新增.pdf
為副檔名並將檔案複製到我的本機磁碟機(例如C:\temp\dest
等)嗎?
我一直在嘗試讓它像這樣工作:
$VT = Import-Csv -Path "C:\test\test.csv" -Delimiter ";" | ForEach {
copy-item -Path C:\test\source\subfolder1\$($_.COL2)*.* -Recurse -Destination C:\test\dest
copy-item -Path C:\test\source\subfolder2\$($_.COL2)*.* -Recurse -Destination C:\test\dest
copy-item -Path C:\test\source\subfolder3\$($_.COL2)*.* -Recurse -Destination C:\test\dest
copy-item -Path C:\test\source\subfolder4\$($_.COL2)*.* -Recurse -Destination C:\test\dest
}
但我希望程式碼更簡單,而不是腳本中的所有這些子資料夾。我沒能成功使用該遞歸選項Copy-Item
。我猜我需要Get-ChildItem
在這裡使用,但我一直在嘗試的腳本只是將所有內容從來源複製到目標或執行而不執行任何操作。
我剛剛在本地進行了測試,因此還不需要使用伺服器資料夾。
答案1
嘗試按照以下思路進行操作:
Import-Csv myfile.csv -header "Col1;Col2;Col3;Col4;Col5" | % {
Copy-Item servername:\server\share\$_.pdf C:\temp\
}
我對你想要做什麼做了幾個假設。
- 您的本地文化已設定為某些歐洲文化,因此 csv 需要分號而不是逗號。
- csv 文件中沒有標題。
- 部分檔案名稱包含定位要複製的檔案所需的所有子資料夾資訊。
- 您正在嘗試將所有項目放入臨時資料夾的子資料夾中。
如果這些假設是錯的,你就必須重寫。
答案2
閱讀問題,似乎您想要這樣的東西:
$sourcePath = '\\server\share\folder'
$destination = 'C:\temp\dest'
# make sure the destination folder exists
$null = New-Item -Path $destination -ItemType Directory -Force
# import the data, and get an string array from COL2 from it
# make sure there are no duplicates in this aray and lop through the filenames
(Import-Csv -Path "C:\test\test.csv" -Delimiter ";").COL2 | Sort-Object -Unique | ForEach-Object {
$fileName = '{0}.pdf' -f $_
# try and find this file somewhere in the source path including its subfolders
$original = Get-ChildItem -Path $sourcePath -Filter $fileName -Recurse | Select-Object -First 1
if ($original) {
$original | Copy-Item -Destination
}
else {
Write-Warning "File '$FileName' could not be found"
}
}