Powershell script error - Error: You cannot call a method on a null-valued expression.
I've got a script set up to sync a local folder with the remote one. I have copy/pasted the snippet from this website.
It will connect and start syncing files, but for some reason when it gets to the end it will throw this error:
Here is the code I'm using:
It will connect and start syncing files, but for some reason when it gets to the end it will throw this error:
I've got some error handling set up and this seems to interfere with it, thinking something is wrong. I can set it up to ignore the error, but I would rather not if possible.Error: You cannot call a method on a null-valued expression.
Here is the code I'm using:
try { # Set up session options $sessionOptions = New-Object WinSCP.SessionOptions -Property @{ Protocol = [WinSCP.Protocol]::Ftp HostName = $ftp_server UserName = $username Password = $password FtpSecure = [WinSCP.FtpSecure]::Explicit } $session = New-Object WinSCP.Session try { # Will continuously report progress of synchronization $session.add_FileTransferred( { FileTransferred($_) } ) # Will continuously report progress of transfer $session.add_FileTransferProgress( { FileTransferProgress($_) } ) # Connect $session.Open($sessionOptions) $transferOptions = New-Object WinSCP.TransferOptions $transferOptions.ResumeSupport.State = [WinSCP.TransferResumeSupportState]::On #$transferOptions.ResumeSupport = [WinSCP.TransferResumeSupport]:: # Synchronize files $synchronizationResult = $session.SynchronizeDirectories( [WinSCP.SynchronizationMode]::Local, #Local is synced to match remote $local_sync_folder, #Local repository $remote_sync_folder, #Remote repository $False, #Delete remove files not in local repository $True, #Do not sync in mirror mode [WinSCP.SynchronizationCriteria]::Time, #Sync based on timestamp $transferOptions ) # Throw on any error $synchronizationResult.Check() } finally { # Disconnect, clean up $session.Dispose() } #Output elapsed time $stopwatch.Stop() $time = $stopwatch.ElapsedMilliseconds/1000 LogWrite "Session complete, time Elapsed: $time seconds" "Time Elapsed: $time seconds" break; #exit 0 } catch { Write-Host "Error: $($_.Exception.Message)" LogWrite "Error: $($_.Exception.Message)" $attempt++ #exit 1 }