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="" ;
smtpserver="mailhost"
}
#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"
UserName = "XXXXXXXXXXXXXXXX"
SshHostKeyFingerprint = "XXXsa-sha2-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
SshPrivateKeyPath = "E:\Scripts\Random\sftp\privatkey.ppk"
}
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Transfer files
$session.putFiles($key, $FileList[$key]).Check()
}
catch
{
$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"
}
finally
{
$session.Dispose()
Write-Output "Closed Connection for $FileList[$key]" >> "E:\Scripts\Random\Log.txt"
}
start-sleep -Seconds 90
}
}
else
{
$NotifyEmail.subject = "Latest File Not Generated"
$NotifyEmail.body = "The Latest $DeleteFile and $UploadFile has not been generated "
Send-MailMessage @NotifyEmail
}