Advertisement
Guest User

Untitled

a guest
Jan 2nd, 2025
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.67 KB | None | 0 0
  1. [CmdletBinding()]
  2. param (
  3.  
  4. [Parameter(Mandatory=$false, HelpMessage = "SFTP server to copy to")]
  5. [string] $SFTPHost = "lfoh-sftp-data"
  6. ,
  7. [Parameter(Mandatory=$false, HelpMessage = "SFTP host fingerprint - use FileZilla to find this")]
  8. [string] $SFTPFingerprint = "ssh-rsa 2048 ...."
  9. ,
  10. [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 !")]
  11. [string] $SFTPRemotePath = '/users/oodle_transfers/Out/' ##? note: the ending '/' is important, files will be copied to this folder !
  12. ,
  13. [Parameter(Mandatory=$false, HelpMessage = "Will send report to these recipients")]
  14. [string[]] $EmailRecipients = @( "[email protected]")
  15. ,
  16. [Parameter(Mandatory=$false, HelpMessage = "Email sender (SMTP, does not need mailbox!)")]
  17. [string] $EmailFrom = "[email protected]"
  18. ,
  19. [Parameter(Mandatory=$false, HelpMessage = "Default email subject")]
  20. [string] $EmailSubject = "Oodle_Transfers"
  21. ,
  22. [Parameter(Mandatory=$false, HelpMessage = "Default email body")]
  23. [string] $EmailBody = "Find attached the transcript"
  24. ,
  25. [Parameter(Mandatory=$false, HelpMessage = "Default SMTP server")]
  26. [string] $EmailSMTPServer = "smtprelay.domain.com"
  27. ,
  28. [Parameter(Mandatory=$false, HelpMessage = "Path to source folder")]
  29. [string] $SourceLANDriveFolder = '\\domain.com\ldms-databins\bondbin\Oodle_Output' # "\\bh-filestore\ICT_Share\Temp\Oodle\In" #
  30. ,
  31. [Parameter(Mandatory=$false, HelpMessage = "Temporary folder")]
  32. [string] $LocalTransferFolder = "D:\temp\output" # 'D:\Scripts\LFO\Oodle\In'
  33. ,
  34. [Parameter(Mandatory=$false, HelpMessage = "Weather or not clear the 'LocalTransferFolder' after the upload; defaults to true")]
  35. [boolean]$ClearTransitFolder = $true
  36. ,
  37. [Parameter(Mandatory=$false, HelpMessage = "We only want to process the files from the last N days")]
  38. [int32]$DaysToKeep = 1
  39.  
  40. )
  41.  
  42. ## SFTP Connection details
  43. $SFTPCredential = $secret:SFTPCredentialOODLE_DEV ##? This should be in Variables > Secrets of PSU!
  44. $SFTPUser = $SFTPCredential.UserName
  45. $SFTPPassword = $SFTPCredential.Password
  46.  
  47. $EmailSubject = $($EmailSubject + " - " + $(Get-Date -Format yyyy-MM-dd_HH-mm))
  48.  
  49. ## Used for accessing shared drive locations for source
  50. $LANCredential = $secret:SVC_FileShareTasks
  51. Write-Verbose -Verbose "Using credential: $($LANCredential.UserName)"
  52.  
  53. ## Parameters for TRANSCRIPT
  54. $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
  55. $FileDate = (Get-Date).ToString("MMddyyyy-hhmmss-tt") ## Store current time stamp
  56.  
  57. ## SOURCE details
  58. $FileNamesToCopy = @(
  59. "38_AgedDebt",
  60. "Oodle_DailyAccounts",
  61. "Oodle_CustomerFlag",
  62. "Oodle_CustomerDetails",
  63. "Oodle_LoanProfiles",
  64. "Oodle_Transactions",
  65. "Oodle_MonthlyAccounts"
  66. )
  67.  
  68.  
  69.  
  70. ## FUNCTIONS
  71. Function Copy-ToTempFolder {
  72. <#
  73. .SYNOPSIS
  74. Function to copy files before the transfer to a temporary folder. Can be omitted.
  75.  
  76. .DESCRIPTION
  77.  
  78. .OUTPUTS
  79. #>
  80. Param (
  81. # Source folder to copy child items from
  82. [Parameter(Mandatory)]
  83. [string]
  84. $SourceFolderPath,
  85.  
  86. # Destination folder to copy child items to
  87. [Parameter(Mandatory)]
  88. [string]
  89. $DestinationFolderPath,
  90.  
  91. # Parameter help description
  92. [Parameter(Mandatory)]
  93. [array]
  94. $FileNamesToInclude
  95. )
  96.  
  97. foreach ($fn in $FileNamesToInclude) {
  98. try {
  99. Get-ChildItem $SourceFolderPath -Filter "*$fn*" | where-Object { $_.LastWriteTime -gt $((Get-Date).AddDays(-$DaysToKeep)) } | ForEach-Object {
  100. Copy-Item -Path $_.FullName -Destination $DestinationFolderPath -Verbose # -WhatIf
  101. }
  102. }
  103. catch {
  104. Write-Host "Failed to copy files matching '$fn': $($_.Exception.Message)"
  105. Write-Host "Stack Trace: $($_.Exception.StackTrace)"
  106. }
  107. }
  108. }
  109.  
  110. function UploadFilesToSFTP {
  111. param (
  112. # SFTP host
  113. [Parameter(Mandatory)]
  114. [string]
  115. $HostName,
  116.  
  117. # SFTP user
  118. [Parameter(Mandatory)]
  119. [string]
  120. $UserName,
  121.  
  122. # SFTP password
  123. [Parameter(Mandatory)]
  124. [System.Security.SecureString]$Password,
  125.  
  126. # Source folder
  127. [Parameter(Mandatory)]
  128. [string] $LocalPath,
  129.  
  130. # Remote folder
  131. [Parameter(Mandatory)]
  132. [string] $RemotePath,
  133.  
  134. # SFTP host fingerprint
  135. [Parameter(Mandatory)]
  136. [string] $SshHostKeyFingerprint,
  137.  
  138. [Parameter(Mandatory=$false)]
  139. [switch]$WipesourceFolder
  140. )
  141.  
  142. # Load the WinSCP assembly
  143. Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
  144.  
  145. # Convert the secure string to an unsecure string for WinSCP
  146. $unsecurePassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto(
  147. [Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)
  148. )
  149.  
  150. # Setup session options
  151. $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
  152. Protocol = [WinSCP.Protocol]::Sftp
  153. HostName = $HostName
  154. UserName = $UserName
  155. Password = $unsecurePassword
  156. SshHostKeyFingerprint = $SshHostKeyFingerprint
  157. PortNumber = 2222
  158. }
  159.  
  160. # Create a new session
  161. $session = New-Object WinSCP.Session
  162.  
  163. try {
  164. # Open the session
  165. $session.Open($sessionOptions)
  166.  
  167. # Upload files
  168. $transferOptions = New-Object WinSCP.TransferOptions
  169. $transferOptions.TransferMode = [WinSCP.TransferMode]::Ascii # Change to 'Text' if necessary
  170.  
  171. $transferOperation = $session.PutFiles("$LocalPath\*", $RemotePath, $False, $transferOptions)
  172.  
  173. # Check for any errors
  174. $transferOperation.Check()
  175. Write-Host "Transfer succeeded: $($transferOperation.Transfers.Count) file(s) uploaded."
  176.  
  177. # Wipe transit folder after the transfer
  178. if($WipesourceFolder.IsPresent){
  179. Get-ChildItem $LocalPath -Recurse | Remove-Item -Force -Recurse -Verbose -ErrorAction Continue
  180. }
  181.  
  182. }
  183. catch {
  184. Write-Host "Error: $($_.Exception.Message)"
  185. Write-Host "Stack Trace: $($_.Exception.StackTrace)"
  186. }
  187. finally {
  188. # Close the session
  189. $session.Dispose()
  190. }
  191. }
  192.  
  193. ## Start TRANSCRIPT
  194. if (-not (Test-Path $CurrentPath\Logs)) { New-Item -Path $CurrentPath\Logs -ItemType Directory }
  195. Start-Transcript -path "$CurrentPath\Logs\Oodle-Transcript_$FileDate.txt" -NoClobber
  196.  
  197. # Generate a random drive letter to avoid conflicts
  198. $driveLetter = (69..89 | Get-Random | ForEach-Object{[char]$_}) + ":" # Random letter from E-Y
  199.  
  200. try {
  201. # Map the network drive with credentials
  202. Write-Verbose -Verbose "Using drive: $driveLetter during transfer"
  203. New-PSDrive -Name $driveLetter[0] -PSProvider FileSystem -Root $SourceLANDriveFolder -Credential $LANCredential -ErrorAction Stop -Verbose
  204.  
  205. ## Copy to TRANSIT FOLDER
  206. $SplatToTemp = @{
  207. SourceFolderPath = $SourceLANDriveFolder
  208. DestinationFolderPath = $LocalTransferFolder
  209. FileNamesToInclude = $FileNamesToCopy
  210. }
  211. Write-Verbose "START - Copying items from [$SourceLANDriveFolder] to [$LocalTransferFolder]" -Verbose
  212. Copy-ToTempFolder @SplatToTemp
  213. Write-Verbose "END - Copy finished" -Verbose
  214.  
  215. }
  216. catch {
  217. Write-Error "Failed to map or access drive: $_"
  218. }
  219. finally {
  220. # Always clean up the drive mapping
  221. if (Test-Path "$driveLetter\") {
  222. Remove-PSDrive -Name $driveLetter[0] -Force -Verbose
  223. }
  224. }
  225.  
  226.  
  227.  
  228. ## Upload to SFTP
  229. $SplatToSFTP = @{
  230. HostName = $SFTPHost
  231. UserName = $SFTPUser
  232. SshHostKeyFingerprint = $SFTPFingerprint
  233. LocalPath = $LocalTransferFolder
  234. RemotePath = $SFTPRemotePath
  235. Password = $SFTPPassword
  236. WipesourceFolder = $ClearTransitFolder
  237.  
  238. }
  239. Write-Verbose "START - Uploading items from [$LocalTransferFolder] to [$SFTPHost / $SFTPRemotePath]" -Verbose
  240. UploadFilesToSFTP @SplatToSFTP
  241. Write-Verbose "END - Upload finished" -Verbose
  242.  
  243. ## End TRANSCRIPT
  244. Stop-Transcript
  245.  
  246. Start-Sleep -Seconds 5
  247.  
  248. ## SEND JOB LOG
  249. try{
  250. foreach ($EmailTo in $EmailRecipients) {
  251.  
  252. # Send-MailMessage -To $EmailTo -From $EmailFrom -Subject $EmailSubject -Body $EmailBody -Attachments "$CurrentPath\Logs\Oodle-Transcript_$FileDate.txt" -SmtpServer $EmailSMTPServer -Verbose -ErrorAction Stop
  253.  
  254. $EmailParams = @{
  255. To = $EmailTo
  256. From = $EmailFrom
  257. Subject = $EmailSubject
  258. Body = $EmailBody
  259. Attachments = "$CurrentPath\Logs\Oodle-Transcript_$FileDate.txt"
  260. Server = $EmailSMTPServer
  261. Verbose = $true
  262. ErrorAction = 'Stop'
  263. Port = 25
  264. SkipCertificateValidatation = $true # extra parameter for "Send-EmailMessage" function
  265. }
  266.  
  267. Send-EmailMessage @EmailParams
  268.  
  269. }
  270. } catch {
  271. Write-Output "Email sending failed. Reason: $($_.Exception.Message)"
  272. Continue
  273. }
  274.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement