基于文本文件将多个文件复制到多个目标

Copy multiple files to multiple destination based on text file

我想通过创建目录将文本文件中指定的文件列表复制到目标列表。我有一个 Excel 文件,其中有 2 列,源和目标,每个源都有一个目标。

示例来源:

\10.0.0.1\share\abd.nsf
\20.0.0.1\share\red.nsf

示例目标:

\10.0.0.2\share\abd\
\10.0.0.2\share\red\

目前我正在使用下面的代码,但是涉及n行,所以很乏味。

copy-item "\10.0.0.1\share\abd.nsf" -destination (New-item "\10.0.0.2\share\abd\" -Type container -force) -force
copy-item "\20.0.0.1\share\red.nsf" -destination (New-item "\10.0.0.2\share\red\" -Type container -force) -force
$source = get-content c:\source.txt
$destination = get-content c:\destination.txt
$Count= $source.Count
$i = 0

For($i -eq 0;$i -Lt $count; $i++){
Try{new-item -itemtype directory $destination[$i]}
Catch {}
Finally{copy-item $source[$i] $destination[$i]}
}

文本文件中的源和目标应该是相同的顺序

这是一个相当简单的问题。将您的 Excel 文件设为 2 列 csv,其中列标记为源和目标。您不必使用那些只知道如果您的不同,您需要调整代码中调用的属性。

$path = "c:\path\to\file.csv"
$jobs = Import-CSV $path
$jobs | ForEach-Object{
    # Check if the target folder exists. If not create it.
    If(-not (Test-Path -PathType Container $_.destination)){New-item "$_.destination" -Type Container -Force}

    # If the source file exists copy it to the destination directory. 
    If(Test-Path $_.Source){Copy-Item $_.Source $_.Destination -Force}
}

如果不存在则创建目标目录(路径可能仍然错误但总比没有好。)。然后将文件复制到目的地,假设它也存在。