Infinite loop to copy folder content from source to destination...

I created the script below which runs in an infinite loop that robocopies the content from D:\1_DIR to D:\2_DIR and then removes the content of D:\1_DIR after that is complete.

While this works in principle, I have concerns that when “new” content gets added to the D:\1_DIR “source” folder and the copy process is initiated/running that if it occurs during the loop at the time of the remove-item command, this might “break” the copy operation.

So far I haven’t ran into that problem and the sleep time will actually be once an hour versus once a minute, but I have concerns that something may not be right and this script may not be full proof to ensure that it always copies all content from D:\1_DIR to D:\2_DIR before wiping D:\1_DIR. Are my concerns unfounded or is there something I need to add to ensure this doesn’t happen. Thanks in advance!


$source = "D:\1_DIR"
$destination = "D:\2_DIR"

     $test = Test-Path $source\*
     If ($test -eq "True") {
          robocopy.exe "$source" "$destination" /E | Out-Null
          remove-item -Path "Microsoft.PowerShell.Core\FileSystem::$source\*" -recurse
      sleep 60

How is this script getting triggered. Are you running once and then having continuously run in the background? If so, I would suggest creating a scheduled task on a server and have it run every hour instead of using the while loop.

As far as it “breaking”, you can add some error handling in your code. Try/Catch block for the Remove-Item Cmdlet. The robocopy you can use an if/else statement and get the $LASTEXITCODE from the robocopy. You can find what the exit codes are from here:

The server version and article is old, but the exit codes are the same for later versions of Windows.


With /xo option, Robocopy does an incremental copy, hence frequent removal is not required. You can have the removal process later in another schedule.

Thanks. Yes, I would currently have it set just run actively and execute the instructions once an hour, but may go the scheduled task route as mentioned.

As far as robocopy, I actually want the source directory wiped each time because this is going to be a drop-box for SCCM application package content where the developer drops the code in there, I then have the script copy it to the SCCM source content location and then wipe the original source location it was copied from and then it runs an end to end process to create the SCCM application package and distribute the content and deploy the application, etc.

Gotcha. You could use the /move switch in Robocopy.

Moves files and directories, and deletes them from the source after they are copied

Source: robocopy | Microsoft Learn