3

I have a program that copies folders and files recursively. example:

Copy-Item -path "$folderA" -destination "$folderB" -recurse 

Sometimes the files do not copy. Is there a way to "step inside the recursion" or a better way to do it, so I can enable some kind of error checking during the process rather than after wards. Possibly even do a Test-Path and prompt for a recopy?

alphadev
  • 1,529
  • 5
  • 18
  • 20
  • stej - didn't realize that was something to do with answered questions - went back and updated them - thx – alphadev Sep 29 '10 at 02:54

1 Answers1

4

You can. For example the following code snippet will actually copy and check each file for possible errors. You can also put your custom code at the beginning to check for some prerequisites:

get-childItem $source -filter *.* | foreach-object {
    # here you can put your pre-copy tests...

    copy-item $_.FullName -destination $target -errorAction SilentlyContinue -errorVariable errors
    foreach($error in $errors)
    {
        if ($error.Exception -ne $null)
        {
            write-host -foregroundColor Red "Exception: $($error.Exception)"
        }
        write-host -foregroundColor Red "Error: An error occured during copy operation."
    }
}
David Pokluda
  • 10,693
  • 5
  • 28
  • 26
  • I am not sure if global variable $Error didn't exist back in 2010, but today, you would get _Cannot overwrite variable Error because it is read-only or constant_, I would recommend to change `errors` too just for consistency: `... -errorVariable CopyErrors` `foreach ($ce in $CopyErrors) {` – papo Mar 12 '18 at 10:01