[英]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.