0
votes

I'm drafting a powershell script to manually backup some DC's. The backups need to be moved from one folder to another and I am using Get-ChildItem -Filter "Backup*" to select the backup files, then robocopy to move them.

It works but I would like to add in a trap and custom error message "Error Copying Local Backup from XX to SystemStateBackup" if the source or destination path is incorrect. I would also like to pipe any errors to a log file.

The original with no trap is

 Get-ChildItem f:\WindowsImageBackup\ITUPW-PRODDC7 -Filter "Backup*" -Name | ForEach-Object { 
 robocopy "f:\WindowsImageBackup\ITUPW-PRODDC7\$_" "f:\WindowsImageBackup\ITUPW-PRODDC7\SystemStateBackup\$_" /Z /S /MOVE /njh /njs /ndl /nc /ns /np /nfl}

The trap will work if I only use part of the code

Trap {"Error Copying Local Backup from XX to SystemStateBackup";Continue} Get-ChildItem f:\WindowsImageBackup\ITUPW-PRODDC7 -Filter "Backup*" -Name -ea "Stop"

But it won't work this way

Trap {"Error Copying Local Backup from XX to SystemStateBackup";Continue} Get-ChildItem f:\WindowsImageBackup\ITUPW-PRODDC7 -Filter "Backup*" -Name | ForEach-Object { 
robocopy "f:\WindowsImageBackup\ITUPW-PRODDC7\$_" "f:\WindowsImageBackup\ITUPW-PRODDC7\SystemStateBackup\$_" /Z /S /MOVE /njh /njs /ndl /nc /ns /np /nfl} -ea "Stop"

It results in the following powershell error

Get-ChildItem : Cannot find path 'F:\WindowsImageBackup\ITUPW-PRODDC' because it does not exist. At line:1 char:88 + Trap {"Error Copying Local Backup from XX to SystemStateBackup";Continue} Get-ChildItem <<<< f:\WindowsImageBackup\I TUPW-PRODDC -Filter "Backup*" -Name | ForEach-Object { robocopy "f:\WindowsImageBackup\ITUPW-PRODDC7\$" "f:\WindowsIma geBackup\ITUPW-PRODDC7\SystemStateBackup\$" /Z /S /MOVE /njh /njs /ndl /nc /ns /np /nfl} -ea "Stop" + CategoryInfo : ObjectNotFound: (F:\WindowsImageBackup\ITUPW-PRODDC:String) [Get-ChildItem], ItemNotFoun dException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

Any advice would be greatly appreciated.

Thank you for you time.

Amelia - A sys admin who drew the short straw

1
What version of PowerShell are you using. You can tell by typing $host.Andy Arismendi
Have you tried dropping the -filter and just using Get-ChildItem "F:\WindowsImageBackup\ITUPW-PRODDC7\Backup*"user847990

1 Answers

0
votes

You are applying the -ea "Stop" to the foreach rather than to the Get-ChildItem. Move it before the pipe |

For the robocopy, you might want to use $? or $lastexitcode (within the foreach-object) to see if it ran fine.