Hi Here I have written code for upload files from local to sftp location using PowerShell
Please follow the below 2 steps only
Step1: Install the Posh-SSH module for sftp connection, it is the open-source PowerShell module
use the below line to install Posh-SSH Module and please check the latest version as of now 2.1 is available
Install-Module -Name Posh-SSH -RequiredVersion 2.1
Step2: use the below PowerShell script for uploading files to sftp.
Please replace the username, password,sftp server, and file paths wherever require
# Set the credentials
$username= "YourSFTPUserName"
$Password = ConvertTo-SecureString 'YourSFTPPassword' -AsPlainText -Force
$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $username , $Password
# Set local file path, SFTP path, and the backup location path which I assume is an SMB path
$FilePath = "C:\Temp"
$SftpPath = '/PSTest'
$SmbPath = "C:\Temp\backup"
# Set the IP of the SFTP server
$SftpIp = 'Your SFTP Server Name or IP'
# Load the Posh-SSH module before importing need to install please refer to step 1
Import-Module Posh-SSH
# Establish the SFTP connection
$ThisSession = New-SFTPSession -ComputerName $SftpIp -Credential $Credential -AcceptKey -ConnectionTimeout 220
foreach($file in Get-ChildItem $FilePath -Filter *.txt)
{
# Do something
# Upload the file to the SFTP path
Set-SFTPFile -SessionId $ThisSession.SessionId -LocalFile $file.FullName -RemotePath $SftpPath -Overwrite
$file.FullName
}
#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }
# Copy the file to the SMB location
Copy-Item -Filter *.txt -Path "C:\Temp\*" -Destination $SmbPath -Force
# Delete the files from source once backup done
Remove-Item -Filter *.txt -Path "C:\Temp\backup\*.txt" -Force
No comments:
Post a Comment