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

后端 未结 5 2059
孤街浪徒
孤街浪徒 2020-12-08 09:03

I need to copy all *.doc files (but not folders whose names match *.doc) from a network folder \\\\server\\source (including files in

5条回答
  •  佛祖请我去吃肉
    2020-12-08 09:15

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

    Something like this:

    $srcdir = "\\server\source\";
    $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 :-)

提交回复
热议问题