I have a PowerShell script that uses the WinSCP .Net library to get some files from a FTP server.
The script runs automatically over night on a server from a administrator account using Task Scheduler.
The problem is that sometimes (it does not have a pattern or at least I can't figure it out) it gives me an error : "Object reference not set to an instance of an object".
Error:
Exception calling "Open" with "1" argument(s): "Object reference not set to an instance of an object." At C:\user\blabla\powershellscript.ps1:47 char:5 + $session.Open($sessionOptions) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : NullReferenceException
The actual line from the code (line 47) is : $session.Open($sessionOptions)
.
If I run the script or the task from Task Scheduler it runs smoothly and does not give me any error.
PowerShell script:
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
$FileSourcePath = '/path_to_the_file'
Add-Type -Path "C:\WinSCP\WinSCPnet.dll"
# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "ip_to_the_server"
UserName = "correct_username"
Password = "correct_password"
SshHostKeyFingerprint = "correct_sshrsa_fingerprint"
}
$session = New-Object WinSCP.Session
try {
# Connect
$session.Open($sessionOptions)
# Transfer files
$session.GetFiles($FileSourcePath, $FileDestinationPath).Check()
} catch {
$_ | Out-File c:\blabla\errors.txt -Append
} finally {
$session.Dispose()
}