Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [CmdletBinding()]
- param (
- [Parameter(Mandatory=$false, HelpMessage = "SFTP server to copy to")]
- [string] $SFTPHost = "lfoh-sftp-data"
- ,
- [Parameter(Mandatory=$false, HelpMessage = "SFTP host fingerprint - use FileZilla to find this")]
- [string] $SFTPFingerprint = "ssh-rsa 2048 ...."
- ,
- [Parameter(Mandatory=$false, HelpMessage = "path - starting from '/' - on SFTP host to copy files to; note: the ending '/' is important, files will be copied to this folder !")]
- [string] $SFTPRemotePath = '/users/oodle_transfers/Out/' ##? note: the ending '/' is important, files will be copied to this folder !
- ,
- [Parameter(Mandatory=$false, HelpMessage = "Will send report to these recipients")]
- [string[]] $EmailRecipients = @( "[email protected]")
- ,
- [Parameter(Mandatory=$false, HelpMessage = "Email sender (SMTP, does not need mailbox!)")]
- [string] $EmailFrom = "[email protected]"
- ,
- [Parameter(Mandatory=$false, HelpMessage = "Default email subject")]
- [string] $EmailSubject = "Oodle_Transfers"
- ,
- [Parameter(Mandatory=$false, HelpMessage = "Default email body")]
- [string] $EmailBody = "Find attached the transcript"
- ,
- [Parameter(Mandatory=$false, HelpMessage = "Default SMTP server")]
- [string] $EmailSMTPServer = "smtprelay.domain.com"
- ,
- [Parameter(Mandatory=$false, HelpMessage = "Path to source folder")]
- [string] $SourceLANDriveFolder = '\\domain.com\ldms-databins\bondbin\Oodle_Output' # "\\bh-filestore\ICT_Share\Temp\Oodle\In" #
- ,
- [Parameter(Mandatory=$false, HelpMessage = "Temporary folder")]
- [string] $LocalTransferFolder = "D:\temp\output" # 'D:\Scripts\LFO\Oodle\In'
- ,
- [Parameter(Mandatory=$false, HelpMessage = "Weather or not clear the 'LocalTransferFolder' after the upload; defaults to true")]
- [boolean]$ClearTransitFolder = $true
- ,
- [Parameter(Mandatory=$false, HelpMessage = "We only want to process the files from the last N days")]
- [int32]$DaysToKeep = 1
- )
- ## SFTP Connection details
- $SFTPCredential = $secret:SFTPCredentialOODLE_DEV ##? This should be in Variables > Secrets of PSU!
- $SFTPUser = $SFTPCredential.UserName
- $SFTPPassword = $SFTPCredential.Password
- $EmailSubject = $($EmailSubject + " - " + $(Get-Date -Format yyyy-MM-dd_HH-mm))
- ## Used for accessing shared drive locations for source
- $LANCredential = $secret:SVC_FileShareTasks
- Write-Verbose -Verbose "Using credential: $($LANCredential.UserName)"
- ## Parameters for TRANSCRIPT
- $CurrentPath = Split-Path -Parent $PSCommandPath ## Store current folder (the folder where this script is executed) as the "".\logs" folder within this will be used for storing log files
- $FileDate = (Get-Date).ToString("MMddyyyy-hhmmss-tt") ## Store current time stamp
- ## SOURCE details
- $FileNamesToCopy = @(
- "38_AgedDebt",
- "Oodle_DailyAccounts",
- "Oodle_CustomerFlag",
- "Oodle_CustomerDetails",
- "Oodle_LoanProfiles",
- "Oodle_Transactions",
- "Oodle_MonthlyAccounts"
- )
- ## FUNCTIONS
- Function Copy-ToTempFolder {
- <#
- .SYNOPSIS
- Function to copy files before the transfer to a temporary folder. Can be omitted.
- .DESCRIPTION
- .OUTPUTS
- #>
- Param (
- # Source folder to copy child items from
- [Parameter(Mandatory)]
- [string]
- $SourceFolderPath,
- # Destination folder to copy child items to
- [Parameter(Mandatory)]
- [string]
- $DestinationFolderPath,
- # Parameter help description
- [Parameter(Mandatory)]
- [array]
- $FileNamesToInclude
- )
- foreach ($fn in $FileNamesToInclude) {
- try {
- Get-ChildItem $SourceFolderPath -Filter "*$fn*" | where-Object { $_.LastWriteTime -gt $((Get-Date).AddDays(-$DaysToKeep)) } | ForEach-Object {
- Copy-Item -Path $_.FullName -Destination $DestinationFolderPath -Verbose # -WhatIf
- }
- }
- catch {
- Write-Host "Failed to copy files matching '$fn': $($_.Exception.Message)"
- Write-Host "Stack Trace: $($_.Exception.StackTrace)"
- }
- }
- }
- function UploadFilesToSFTP {
- param (
- # SFTP host
- [Parameter(Mandatory)]
- [string]
- $HostName,
- # SFTP user
- [Parameter(Mandatory)]
- [string]
- $UserName,
- # SFTP password
- [Parameter(Mandatory)]
- [System.Security.SecureString]$Password,
- # Source folder
- [Parameter(Mandatory)]
- [string] $LocalPath,
- # Remote folder
- [Parameter(Mandatory)]
- [string] $RemotePath,
- # SFTP host fingerprint
- [Parameter(Mandatory)]
- [string] $SshHostKeyFingerprint,
- [Parameter(Mandatory=$false)]
- [switch]$WipesourceFolder
- )
- # Load the WinSCP assembly
- Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
- # Convert the secure string to an unsecure string for WinSCP
- $unsecurePassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto(
- [Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)
- )
- # Setup session options
- $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
- Protocol = [WinSCP.Protocol]::Sftp
- HostName = $HostName
- UserName = $UserName
- Password = $unsecurePassword
- SshHostKeyFingerprint = $SshHostKeyFingerprint
- PortNumber = 2222
- }
- # Create a new session
- $session = New-Object WinSCP.Session
- try {
- # Open the session
- $session.Open($sessionOptions)
- # Upload files
- $transferOptions = New-Object WinSCP.TransferOptions
- $transferOptions.TransferMode = [WinSCP.TransferMode]::Ascii # Change to 'Text' if necessary
- $transferOperation = $session.PutFiles("$LocalPath\*", $RemotePath, $False, $transferOptions)
- # Check for any errors
- $transferOperation.Check()
- Write-Host "Transfer succeeded: $($transferOperation.Transfers.Count) file(s) uploaded."
- # Wipe transit folder after the transfer
- if($WipesourceFolder.IsPresent){
- Get-ChildItem $LocalPath -Recurse | Remove-Item -Force -Recurse -Verbose -ErrorAction Continue
- }
- }
- catch {
- Write-Host "Error: $($_.Exception.Message)"
- Write-Host "Stack Trace: $($_.Exception.StackTrace)"
- }
- finally {
- # Close the session
- $session.Dispose()
- }
- }
- ## Start TRANSCRIPT
- if (-not (Test-Path $CurrentPath\Logs)) { New-Item -Path $CurrentPath\Logs -ItemType Directory }
- Start-Transcript -path "$CurrentPath\Logs\Oodle-Transcript_$FileDate.txt" -NoClobber
- # Generate a random drive letter to avoid conflicts
- $driveLetter = (69..89 | Get-Random | ForEach-Object{[char]$_}) + ":" # Random letter from E-Y
- try {
- # Map the network drive with credentials
- Write-Verbose -Verbose "Using drive: $driveLetter during transfer"
- New-PSDrive -Name $driveLetter[0] -PSProvider FileSystem -Root $SourceLANDriveFolder -Credential $LANCredential -ErrorAction Stop -Verbose
- ## Copy to TRANSIT FOLDER
- $SplatToTemp = @{
- SourceFolderPath = $SourceLANDriveFolder
- DestinationFolderPath = $LocalTransferFolder
- FileNamesToInclude = $FileNamesToCopy
- }
- Write-Verbose "START - Copying items from [$SourceLANDriveFolder] to [$LocalTransferFolder]" -Verbose
- Copy-ToTempFolder @SplatToTemp
- Write-Verbose "END - Copy finished" -Verbose
- }
- catch {
- Write-Error "Failed to map or access drive: $_"
- }
- finally {
- # Always clean up the drive mapping
- if (Test-Path "$driveLetter\") {
- Remove-PSDrive -Name $driveLetter[0] -Force -Verbose
- }
- }
- ## Upload to SFTP
- $SplatToSFTP = @{
- HostName = $SFTPHost
- UserName = $SFTPUser
- SshHostKeyFingerprint = $SFTPFingerprint
- LocalPath = $LocalTransferFolder
- RemotePath = $SFTPRemotePath
- Password = $SFTPPassword
- WipesourceFolder = $ClearTransitFolder
- }
- Write-Verbose "START - Uploading items from [$LocalTransferFolder] to [$SFTPHost / $SFTPRemotePath]" -Verbose
- UploadFilesToSFTP @SplatToSFTP
- Write-Verbose "END - Upload finished" -Verbose
- ## End TRANSCRIPT
- Stop-Transcript
- Start-Sleep -Seconds 5
- ## SEND JOB LOG
- try{
- foreach ($EmailTo in $EmailRecipients) {
- # Send-MailMessage -To $EmailTo -From $EmailFrom -Subject $EmailSubject -Body $EmailBody -Attachments "$CurrentPath\Logs\Oodle-Transcript_$FileDate.txt" -SmtpServer $EmailSMTPServer -Verbose -ErrorAction Stop
- $EmailParams = @{
- To = $EmailTo
- From = $EmailFrom
- Subject = $EmailSubject
- Body = $EmailBody
- Attachments = "$CurrentPath\Logs\Oodle-Transcript_$FileDate.txt"
- Server = $EmailSMTPServer
- Verbose = $true
- ErrorAction = 'Stop'
- Port = 25
- SkipCertificateValidatation = $true # extra parameter for "Send-EmailMessage" function
- }
- Send-EmailMessage @EmailParams
- }
- } catch {
- Write-Output "Email sending failed. Reason: $($_.Exception.Message)"
- Continue
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement