Post a reply

Options
Add an Attachment

If you do not want to add an Attachment to your Post, please leave the Fields blank.

(maximum 10 MB; please compress large files; only common media, archive, text and programming file formats are allowed)

Options

Topic review

martin

Re: get local filename after transfer so i can attach to email

You get the target path in $transfer.Destination
netrecov

get local filename after transfer so i can attach to email

Hello I am trying to get the filename of the file just downloaded with the localpath so i can attach it to an email.
here is the code
[code]param (
$localPath = "C:\upload\*",
$remotePath = "/home/user/",
$backupPath = "C:\backup\"
)

try
{
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"

# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
$sessionOptions.HostName = "example.com"
$sessionOptions.UserName = "user"
$sessionOptions.Password = "mypassword"
$sessionOptions.SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"

$session = New-Object WinSCP.Session

try
{
# Connect
$session.Open($sessionOptions)

# Upload files, collect results
$transferResult = $session.PutFiles($localPath, $remotePath)

# Iterate over every transfer
foreach ($transfer in $transferResult.Transfers)
{
# Success or error?
if ($transfer.Error -eq $Null)
{
Write-Host ("Upload of {0} succeeded, moving to backup" -f
$transfer.FileName)
Send-MailMessage -From $From -to $To -Cc $Cc -Bc $Bc -Attach $session.GetFileInfo(Filename) -Subject $Subject -Body $Body -SmtpServer $SMTPServer
# Upload succeeded, move source file to backup
Move-Item $transfer.FileName $backupPath
}
else
{
Write-Host ("Upload of {0} failed: {1}" -f
$transfer.FileName, $transfer.Error.Message)
}
}
}
finally
{
# Disconnect, clean up
$session.Dispose()
}

exit 0
}
catch [Exception]
{
Write-Host $_.Exception.Message
exit 1
}
[/code][/code]