【问题标题】:Copy file from a directory based on CSV file从基于 CSV 文件的目录中复制文件
【发布时间】:2020-10-17 02:56:00
【问题描述】:

我现在遇到一些关于 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 }

你能帮我解决这个问题吗?

谢谢

【问题讨论】:

  • 刚接触 SO 你可能不知道这一点,但习惯于点击左侧的 ✓ 图标 accept the answer that solved your problem。这将有助于其他有类似问题的人更轻松地找到它,并有助于激发人们回答您的问题。

标签: powershell csv file-copying


【解决方案1】:

我在脚本中提供了 cmets 来帮助你理解我在做什么。

(注意:这可以压缩,但我把它分开了,这样你可以更容易看到。)

# 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 命令中没有给我任何错误。也许我的 CSV 有问题?
  • 您在源文件夹中的文件名是否有扩展名?比如 .txt 或 .csv
  • 如果没有,那么这就是为什么你没有得到任何结果
  • 如果没有扩展名,把$item.File后面的.*去掉就行了
【解决方案2】:

虽然您一直在文件路径中使用正斜杠,但在 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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 2021-12-18
    • 2021-10-01
    • 2010-11-26
    • 1970-01-01
    相关资源
    最近更新 更多