Posh-SSH PowerShell How to get filename and status, and add line to log file

1.6k Views Asked by At

Im trying copy file to SFTP server i use posh shh and if it was successfully moved then I get the filename and add new line in Log file, otherwise i add line that file wasnt move or file not in source dir. I understand how to copy and add line into the log file but i cant bring the right logic in to this script.

Pls see my code below:

# SFTP Upload of Inventory From CSV files to WPEngine SFTP. Requires installation of Posh-SSH 
# Install-Module -Name Posh-SSH (https://github.com/darkoperator/Posh-SSH)
 
# Set the credentials
$Password = ConvertTo-SecureString 'almighty1992' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ('sftpuser', $Password)
 
# Set local file path and SFTP path
$FilePath1 = "D:\TEST.txt"

$SftpPath = '/shared/'
 
# Set the Hostname of the SFTP server
$SftpServer = '192.168.1.215'
 
# Load the Posh-SSH module
#Import-Module Posh-SSH
 
# Establish the SFTP connection
$ThisSession = New-SFTPSession -ComputerName $SftpServer -Credential $Credential -AcceptKey -Port 22
 
# Upload the files to the SFTP path
Set-SFTPFile -SessionId ($ThisSession).SessionId -Localfile $FilePath1 -RemotePath $SftpPath -Overwrite

 
#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }

Add-Content D:\LOG.TXT "Test" 

Code which i dont know how to add. If im right understand i need to check that file exist in source directory.

#check source file exist Test-Path -Path D:\TEST.txt -PathType Leaf

lists sftp directory files after file was copied $FilePath = Get-SFTPChildItem -sessionID $SFTPSession.SessionID -path $SftpPath

#For each file ForEach ($LocalFile in $FilePath) {

if($LocalFile.name -eq "." -Or $LocalFile.name -eq ".." )
{
      Write-Host "Files Ignored!"
}
else
{
    Write-Host $LocalFile
    Get-SFTPFile -SessionId $SFTPSession.SessionID -LocalPath $LocalPath -RemoteFile $localfile.fullname 

Force }

}

1

There are 1 best solutions below

0
On

Get the list of files from the SFTP session

$Files = (Get-SFTPChildItem -SessionId $Session.SessionId -Path "$sftpRemotePath") | Select-object Name,FullName,Length | Sort-Object FullName

Filter the /. and /..

$msgFiles = $Files | where-object {$_.FullName -ne "/." -and $_.FullName -ne "/.."}

Add the files to the log separated by new line after each file

$filelist = $msgFiles | Foreach-Object " ${($_.Name)`n"}

Finally add the filelist to the log file

Add-Content -value $filelist -Path $logfile

Note: change the variables where necessary.