darkoperator / Posh-SSH

PowerShell Module for automating tasks on remote systems using SSH
BSD 3-Clause "New" or "Revised" License
970 stars 226 forks source link

Error Message: #< CLIXML The Writer is closed or in error state. #546

Open ghanshyam-verma opened 10 months ago

ghanshyam-verma commented 10 months ago

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 '{{SFTPSERVER}}' -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 '{{REMOTEPATH}}' -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;

MVKozlov commented 10 months ago

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)