0

How do I check if the copy was successful before the script goes to the next command?

    $src_dir_local = 'D:\temp\tobemoved\'
$dst_dir_local = 'D:\temp\moved\'
$log_dir = 'D:\temp\log\'
$log_file = 'backup.log'
$ofs_char = "`n"
$curr_date = Get-Date -UFormat '%Y-%m-%d'
$curr_date_time = Get-Date
$s3_bucket = 's3://mybucket/'
$s3_storage_class = 'STANDARD_IA'
$files = Get-ChildItem $src_dir_local

write-output $src_dir_local + $file + $curr_date
write-output $s3_command

aws s3 ls 

write-output 'looping through files....'
foreach($f in $files){
    $outputfilename = $f.Name

    $s3_move_command = 'time aws s3 cp --quiet' + ($src_dir_local + $outputfilename + ' ' + $s3_bucket + $curr_date + '/' + $outputfilename + ' --storage-class ' + $s3_storage_class)


    write-output $outputfile
    write-output 'Start process'

    Invoke-Expression $s3_move_command

    move-item -path ($src_dir_local + $outputfilename) -destination ($dst_dir_local + '_mvd_' + $outputfilename) -whatif

    write-output 'End process'
    write-output 'Start moving process'

    $log_message = ($ofs_char + 'File moved ' + $outputfile + ' ' + $((Get-Date).ToString()))
    if(Test-Path ($log_dir + $log_file)){
        Add-Content ($log_dir + $log_file)  $log_message
    }else{
        New-Item -path $log_dir -name $log_file -type 'file' -value 'Initial log '
        Add-Content ($log_dir + $log_file) $log_message
    }
}
gdubs
  • 2,724
  • 9
  • 55
  • 102

1 Answers1

1

In general, you would write:

aws s3 cp $src $dst

If ($lastexitcode -eq 0) {
   ...
} Else {
   ...
}

See the docs here.

If you must use Invoke-Expression, then see the linked Stack Overflow answer.

Alex Harvey
  • 14,494
  • 5
  • 61
  • 97