Copy Backup files to S3

I somehow got this script working, but the write host command is displaying “no files to upload” message multiple times since its inside foreach loop and keeps iterating. I would like to display this message only once. Any help here would be much appreciated.

$Extensions = “.diff”,“.bak”,“.trn”
$Today = (Get-date)
$Bucket_Name = (Invoke-Sqlcmd -Query “select Bucket_Name from msdb.dbo.BackConfigInfo”).Bucket_Name
$AccessKey = (Invoke-Sqlcmd -Query “select AccessKey from msdb.dbo.BackConfigInfo”).AccessKey
$Secret_Key = (Invoke-Sqlcmd -Query “select Secret_key from msdb.dbo.BackConfigInfo”).Secret_key
Set-AWSCredential -AccessKey $AccessKey -SecretKey $Secret_Key -StoreAs default
$HOSTNAME = $env:computername
$HOSTNAME = $HOSTNAME + ‘********’
$ID = (Get-EC2Tag | Where-Object {$.Key -eq ‘Hostname’ -and $.Value -eq $HOSTNAME})
$App = (Get-EC2Tag | Where-Object {$.ResourceId -eq $ID.ResourceId -and $.Key -eq ‘Application’})
$tag = $App.Value
$sourceloc = (Invoke-Sqlcmd -Query “EXEC master.dbo.xp_instance_regread ‘HKEY_LOCAL_MACHINE’, ‘Software\Microsoft\MSSQLServer\MSSQLServer’,‘BackupDirectory’”).Data

Get-ChildItem -Path $sourceloc -Recurse | Foreach-Object {
$BackupFileOnDisk = $.Name
if(Get-S3Object -BucketName $Bucket_Name | where{$
.Key -cmatch $BackupFileOnDisk})
Write-host “No files to Upload”
Write-host “$BackupFileOnDisk not in $Bucket_Name”
Write-S3Object -BucketName $Bucket_Name $BackupFileOnDisk -Folder $sourceloc -KeyPrefix $HOSTNAME\Backup -TagSet @{Key=“Application”;Value=“$tag”} -ServerSideEncryption ****** -Recurse

You have several places in your code where you have pipelining | where you are not using the pipeline variable denoted by $_ and not just $ or $. like $.Key should be $_.Key

See for more info about automatic variables.

oops, my bad, somehow I missed the $_.key, actually I am getting the output like this

However I need this message to be printed only once. Any suggestions on this please

Either pull that code out of the loop or implement different logic on the trigger of that code path.