问题
I want to copy list of files specified in text file to list of destination by creating directory. I have one Excel file in which there are 2 columns, source and destination, each source has a destination.
Example Source:
\\10.0.0.1\share\abd.nsf
\\20.0.0.1\share\red.nsf
Example Dest:
\\10.0.0.2\share\abd\
\\10.0.0.2\share\red\
Currently I am using below code, but involves n number of lines so it is tedious.
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
回答1:
This is a rather simple one. Make your Excel file a 2 column csv where the columns are labelled Source and Destination. You don't have to use those just know that if yours differ that you need to adjust the properties called in the code.
$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}
}
Creates the destination directory if it does not exist (It is possible the path is still wrong but its better than nothing.). Then copy the file, assuming it also exists, to the destination.
回答2:
$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]}
}
Source and destination in text file should be in same order
来源:https://stackoverflow.com/questions/34503413/copy-multiple-files-to-multiple-destination-based-on-text-file