[英]Copy file from a directory based on CSV file
我現在有一些關於 PowerShell 中的代碼的問題。
我想在 PowerShell 中編寫一個腳本,以根據 CSV 文件將文件從一個文件夾復制到另一個現有文件夾:
例如,我在 CSV 中有兩列:一列用於不帶擴展名的文件名,另一列用於我要將文件復制到的路徑。
csv 示例:
File,Pathdestinationfile
test1_000,C:/Documents/test1
所以我需要從諸如 C:/Source 之類的路徑獲取我的文件,並將其復制到我的 CSV 中提到的特定目標文件路徑。
這是我目前擁有的代碼,但它不起作用:
Import-CSV C:\Users\T0242166\Documents\SCRIPT_CSV\testscript.csv |
Where-Object Name -Like $_.File |
foreach { Copy-item -Path "C:/Source" -Destination $_.Filepathdestination -Recurse }
你能幫我解決這個問題嗎?
謝謝
我在腳本中提供了注釋以幫助您了解我在做什么。
(注意:這可以壓縮,但我把它分開了,這樣你就可以更容易地看到它。)
# Define your constant variable
$sourceFolder = "C:\Source"
# Import Your CSV
$content = Import-Csv "C:\Users\T0242166\Documents\SCRIPT_CSV\testscript.csv"
# Iterate Through Your Objects From CSV
foreach ($item in $content)
{
# Find the file you are looking for
$foundFile = Get-Item -Path ($sourceFolder + "$($item.File).*")
# Copy the file using the FullName property, which is actually the full path, to your destination defined in your csv file.
Copy-Item $foundFile.FullName -Destination ($item.Pathdestinationfile)
}
精簡版:
# Import and Iterate Through Your Objects From CSV
foreach ($item in (Import-Csv "C:\Users\T0242166\Documents\SCRIPT_CSV\testscript.csv"))
{
# Find the file you are looking for and copy it
Copy-Item "C:\Source\$($item.File).*" -Destination $item.Pathdestinationfile
}
另一個精簡版:
Import-Csv "C:\Users\T0242166\Documents\SCRIPT_CSV\testscript.csv" | foreach { Copy-Item "C:\Source\$($_.File).*" -Destination $_.Pathdestinationfile }
盡管您在文件路徑中繼續使用正斜杠,但在 PowerShell 中,這將起作用:
# import the data from the CSV file and loop through each row
Import-CSV -Path 'C:\Users\T0242166\Documents\SCRIPT_CSV\testscript.csv' | ForEach-Object {
# get a list of FileInfo objects based on the partial file name from the CSV
# if you don't want it to find files in subfolders of "C:\Source", take off the -Recurse switch
$files = Get-ChildItem -Path "C:\Source" -Filter "$($_.File).*" -File -Recurse
foreach ($file in $files) {
$file | Copy-Item -Destination $_.Pathdestinationfile
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.