Posh-SSH
Posh-SSH copied to clipboard
Error Message: #< CLIXML The Writer is closed or in error state.
Dear Team,
I am using the posh-ssh module to transfer the files from local machine to SFTP. it always transfers the first file successfully. after that I got the error message for failure. Is there any workaround available for this issue. or I did any mistake in the given code.
motioned below is the code snippet:
Import-Module Posh-SSH;
$Password = ConvertTo-SecureString "{{SFTP_PASSWORD}}" -AsPlainText -Force; $Credential = New-Object System.Management.Automation.PSCredential ('{{SFTP_USERNAME}}', $Password); Write-Output "Credentials were loaded."
Write-Output "Establishing SFTP connection..."; try { $sftpSession = New-SFTPSession -ComputerName '{{SFTP_SERVER}}' -Credential $Credential -AcceptKey; } catch { Write-Output "Connection to SFTP Server failed. Trying again"; Write-Output $_; $sftpSession = New-SFTPSession -ComputerName '{{SFTP_SERVER}}' -Credential $Credential -AcceptKey; }
Write-Output "Getting files to transfer..."; $files = Get-ChildItem -Path '{{LOCAL_FOLDER}}';
Write-Output $files; Write-Output ""
Upload the file to the SFTP path
foreach($file in $files) { try{ Set-SFTPItem -SessionId ($sftpSession).SessionId -Destination '{{REMOTE_PATH}}' -Path $file.Fullname -Force -ErrorAction Stop; Write-Output ($file.FullName + " was successfully transferred."); Remove-Item -LiteralPath $file.Fullname; } catch { Write-Output ("An error occurred for file " + $file.FullName); Write-Output $_; } } Write-Output "Disconnectig from SFTP Server..."; $sftpSession.Disconnect(); Remove-SftpSession -SftpSession $sftpSession;
I got the error message for failure
You forgot to show the message :)
and
try {
$session = new-sftpsession
}
catch {
$session = new-sftpsession
}
is a bad pattern
# much better
$tries = 3;
do {
$tries--
$session = new-sftpsession
} until ($session -or $tries -eq 0)