Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
953 views
in Technique[技术] by (71.8m points)

powershell - How to copy certain files (w/o folder hierarchy), but do not overwrite existing files?

I need to copy all *.doc files (but not folders whose names match *.doc) from a network folder \serversource (including files in all nested folders) to a local folder C:destination without preserving the nested folders hierarchy (i.e. all files should go directly into C:destination and no nested folders should be created in C:destination). In case there are several files with the same name from different subfolders of \serversource, only the first one should be copied and never overwritten then — all conflicting files found later should be skipped (there could be many cases like this, and the skipped files should not be trasferred over the network, otherwise it would take too much time). Here is my attempt to implement it in PowerShell:

cp \serversource* -Recurse -Include *.doc -Container:$false -Destination C:destination

There are at least two problems with this command:

  • It copies folders whose names match *.doc too.
  • In case of conflicting names any file found later is transferred over the network and overwrites the previous one.

Can you suggest how to fix these problems?
Implementations using copy, xcopy, robocopy, cscript or *.bat, *.cmd are also welcome.
The local OS is Windows 8 and the file system is NTFS.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would produce the list of files first and validate as you go through the list.

Something like this:

$srcdir = "\serversource";
$destdir = "C:destination";
$files = (Get-ChildItem $SrcDir -recurse -filter *.doc | where-object {-not ($_.PSIsContainer)});
$files|foreach($_){
    if (!([system.io.file]::Exists($destdir+$_.name))){
                cp $_.Fullname ($destdir+$_.name)
    };
}

So, use Get-ChildItem to list files in source folder matching the filter, pipe through where-object to strip directories out.

Then go through each file in a foreach loop and check if the filename (not Fullname) exists in the destination using the Exists method of the system.io.file .NET class.

If it doesn't, copy, using only original filename (dropping original path).

Use the -whatif option on the copy when testing, so it only displays what it would do, in case result is not what you wanted :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...