PowerShell script, Transfer to SFTP and then rename the local file and move to another folder

Advertisement

vasy.ciuban
Joined:
Posts:
3
Location:
Italy

PowerShell script, Transfer to SFTP and then rename the local file and move to another folder

Guys, you who are great experts can you help me?

I have a set of folders with files inside and a subfolder.
ASSOCIATIONS_IT
ArticleL1_declaration.xlsx
ArticleL2_declaration.xlsx
ArticleL3_declaration.xlsx
 ↳ ARCHIVE

CATALOG
ArticleL1_catalogs.xlsx
ArticleL2_catalogs.xlsx
ArticleL3_catalogs.xlsx
 ↳ ARCHIVE

ITEM
ArticleL1_Master_xxx.xlsx
ArticleL2_Master_xxx.xlsx
ArticleL3_Master_xxx.xlsx
 ↳ ARCHIVE
etc etc.

Each parent folder contains files with a specific prefix and all ending in .xslx.
These files must be sent to an SFTP every night and after they are sent I must add the date and time (timestamp) before the .xslx.
and move them into the ARCHIVE child folder.

If I can also add a email notification with the Office 365 server that would be great.

Can anyone help me as soon as possible in this?

I started from this script but I couldn't rename the file to Name.timestamp.xlsx.
The move and the log I was able to do.
param (
    $localPath = "C:\WEBORDER\ASSOCIATIONS_IT\Article*.xlsx",
    $remotePath = "/",
    $backupPath = "C:\WEBORDER\ASSOCIATIONS_IT\ARCHIVE\"
)
 
try
{
    # Load WinSCP .NET assembly
    Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
 
    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Ftp
        HostName = "hostftp"
        UserName = "username"
        Password = "password"
    }
 
    $session = New-Object WinSCP.Session
    $session.SessionLogPath = "C:\WEBORDER\LOGS\incremental_LOG.log"
 
    try
    {
        # Connect
        $session.Open($sessionOptions)
 
        # Upload files, collect results
        $transferResult = $session.PutFiles($localPath, $remotePath)
 
        # Iterate over every transfer
        foreach ($transfer in $transferResult.Transfers)
        {
            # Success or error?
            if ($transfer.Error -eq $Null)
            {   
 
                Write-Host "Upload of $($transfer.FileName) succeeded, moving to backup"
                # Upload succeeded, move source file to backup
                Move-Item $transfer.FileName $backupPath
            }
            else
            {
                Write-Host "Upload of $($transfer.FileName) failed: $($transfer.Error.Message)"
            }
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
 
    exit 0
}
catch
{
    Write-Host "Error: $($_.Exception.Message)"
    exit 1
}

Reply with quote E-mail

Advertisement

Advertisement

You can post new topics in this forum