SFTP Not Working When Script is Triggered From Task Scheduler

Hi Team

I am having some issues trying to get the sftp working. When I run the sftp Script from Powershell ISE it uploads the file with no issues. However if I try to run it from the Task scheduler calling it via a batch file it does not work.

$NotifyEmail = @{
from="Clown@Circus.com" ;
to= "duck@quack.com","tiger@roar.com" ;
body="" ;
subject="" ;

#Testing if Source path is Accessible

if (-not (Test-path "\\SomeServer\Somepath\DIR1"))


$NotifyEmail.subject = "Path Not Accessible"
$NotifyEmail.body = "The Path \\SomeServer\Somepath\DIR1 is not accessible "
Send-MailMessage @NotifyEmail


#Date in the mmddyyy format

$TodaysDate = (get-date | select -ExpandProperty month).tostring() + (get-date | select -ExpandProperty day).tostring() + (get-date | select -ExpandProperty year).tostring()

#Append the File name to the date to pick the right file

$DeleteFile = "\\SomeServer\Somepath\DIR1\Folder1\" + "Sample1_" + $TodaysDate + ".csv"
$UploadFile = "\\SomeServer\Somepath\DIR1\Folder2\" + "Samle2_" + $TodaysDate + ".csv"


#Test if both the files are available with the correct date

if((Test-Path $DeleteFile) -and (Test-path $UploadFile))


$FileList = @{}

$FileList.add($DeleteFile, "/delete/*" )
$FileList.add($UploadFile,"/Update/*" )

# Load WinSCP .NET assembly
Add-Type -Path "E:\Scripts\Random\sftp\WinSCPnet.dll"

foreach($key in $FileList.keys)


# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "sftp-XXXXXXXX.net"
SshPrivateKeyPath = "E:\Scripts\Random\sftp\privatkey.ppk"

$session = New-Object WinSCP.Session

# Connect

# Transfer files
$session.putFiles($key, $FileList[$key]).Check()



$NotifyEmail.subject = "SFTP Error Has Occured"
$NotifyEmail.body = "Errors have occured trying to Transfer to $sessionOptions.Hostname "
#Send-MailMessage @NotifyEmail
Write-Output "Error Occured for for $FileList[$key]" >> "E:\Scripts\Random\Log.txt"





Write-Output "Closed Connection for $FileList[$key]" >> "E:\Scripts\Random\Log.txt"


start-sleep -Seconds 90





$NotifyEmail.subject = "Latest  File Not Generated"
$NotifyEmail.body = "The Latest $DeleteFile and $UploadFile has not been generated "
Send-MailMessage @NotifyEmail




It’d be worth checking in with the WinSCP folks to see if they need particular privileges, or - more likely - if they’re expecting a full user profile to exist. Scheduled tasks don’t run under a “full” logon session.

Thanks Don for the response will do so