<#
Script: TCS-StuckFileMover.ps
Emil Holgersen, Thales, 2021-03-16
This script moves any transactionfiles in the outgoing fsv subfolders that are more than 2 hours old back into the start folder.
This script is meant as a temporary fix while the devs figure out why some files get stuck on the tcs servers.
Please note that the script includes the year 2021 in the path. It will need modification if intended to run past the end of the year.

Revision 1.1: Changed from using start time for all timestamps in log to using dynamic timestamps. (this was lifted from an old Thales script)
#>

$logfile = 'D:\ifsbosystem\log\FSV.EWOPS.StuckFileMover.log'
$destination = 'D:\IFSBOData\FSV\Outgoing\REJ-P-MDL003V\DCP_ud'
$notprocessedpath = 'D:\IFSBOData\FSV\Outgoing\REJ-P-MDL003V\DCP_ud\2021\*'

Add-Content -Path $logfile -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - Job start"

$files = Get-Item -Path $notprocessedpath | Get-ChildItem -Recurse | Where { $_.Attributes -notcontains 'directory' -and $_.Name -notmatch 'MsgBoxConf.xml' -and $_.CreationTime -le $(Get-Date).AddHours(-2) }

if(-not $files) {
    Add-Content -Path $logfile -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - Job stopping prematurely - No files found"
}
else {
    Add-Content -Path $logfile -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - Found $($files.Count) file(s)"
    foreach($file in $files) {
        try {
            Add-Content -Path $logfile -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - Moving $($file.Name)" 
            $file | Move-Item -Destination $destination -ErrorAction Stop
        }
        catch {
            Add-Content -Path $logfile -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - Failed: $($_.ToString().Trim())" 
        }
    }
        Add-Content -Path $logfile -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - Job complete"
}