I’m having a little trouble finishing a powershell script. The script is to copy two files from an SFTP server. The files are on a directory that will get copied to a shared folder for review and processing.The names of the two files will always be the same except for the extension, which will increment by a random number each time ex. File1.120 and file2.130.
The script is setup to copy over the files from the directory to a shared folder so the appropriate people can review the two files.
• This is a one way copy from the directory to the shared folder and the files on the directory cannot be over-written when copying
• There is a second script that will be ran everyday that checks to see if it is the last working day of the month and if so it will then trigger the file copy script
• I would like for the script to search the directory for the two hardcoded files and only copy the newest ones The problem I run into when trying things like robocopy or something like this is that once the script is ran is no longer copies the two hard coded files but rather will copy a random file that was uploaded that day.
This is the loop that will copy each file.
# Get a list of files from the source folder
$files = Get-SFTPChildItem -SessionId $SessionID -Path "/path/to/dir/"
# Loop through each file and copy
foreach ($file in $files) {
if ($file.Name -match $file1BaseName -or $file.Name -match $file2BaseName) {
$sourceFolder = Join-Path $sourceFolder $file.Name
Get-SFTPItem -Path $file.FullName -Destination $destinationFolder -SessionId $SessionID -Force
Write-Output "File $($file.BaseName) copied to $($destinationFolder)"
}
An example of an if-else statement copying the wrong file
# Get the most recently modified file from the source folder
$mostRecentFile = Get-SFTPChildItem -SessionId $SessionID -Path "/path/to/dir/" | Sort-Object -Descending -Property LastWriteTime | Select-Object -First 1
if ($mostRecentFile -ne $null) {
$sourcePath = $mostRecentFile.FullName
Get-SFTPItem -Path $sourcePath -Destination $destinationFolder -SessionId $SessionID -Force
Write-Output "File $($mostRecentFile.Name) copied to $($destinationFolder)"
} else {
Write-Output "No files were found in the source folder."
}
this is what worked for me.