Re: This Powershell script works except...
You have to call$removeResult.Check()
right after$removeResult = $session.RemoveFiles($RemovalFile)
This worked perfectly.
Thanks so much!
You have to call$removeResult.Check()
right after$removeResult = $session.RemoveFiles($RemovalFile)
$removeResult.Check()
right after $removeResult = $session.RemoveFiles($RemovalFile)
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "sftp-home.our.com"
PortNumber = "12321"
UserName = "*********"
Password = "******************"
SshHostKeyFingerprint = "ssh-rsa 1024 4d:...:71"
}
$session = New-Object WinSCP.Session
try
{
# Date delimiter
$RemovalDate = (Get-Date).Adddays(-3)
# Connect
$session.Open($sessionOptions)
# List of files in the directory
$Directory = $session.ListDirectory("/")
foreach ($FileInfo in $Directory.Files)
# Compare LastWriteTime and ignores directory listing for ".."
{
If ($FileInfo.Name -ne $null)
{
If ($FileInfo.LastWriteTime -lt $RemovalDate -and $FileInfo.Name -ne "..")
{
$RemovalFile = ($FileInfo.Name)
write-host $RemovalFile
$removeResult = $session.RemoveFiles($RemovalFile)
}
}
}
# Throw on error
$removeResult.Check()
exit 0
}
Catch
{
## Error results emailed
$From = "rmtuser@home.our.com"
$To = "rmtuser@home.our.com"
$Date = (Get-Date)
$DateStr = $Date.ToString("MMddyyyy")
$SubjectStr = "Delete Failure " + $($_.Exception.Message)
$Subject = $SubjectStr + $DateStr
$Body = @"
Error:
$($_.Exception.Message)
"@
$SMTPServer = "smtp.hotmail.com"
$SMTPPort = "587"
$password = Get-Content "C:\Pwd2\Pwd.txt" | ConvertTo-SecureString
$login = "rmtuser@home.our.com"
$credentials = New-Object System.Management.Automation.Pscredential -Argumentlist $login,$password
Send-MailMessage -From $From -to $To -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -UseSsl -Port $SMTPPort `
-Credential ($credentials) #-Attachments $Attachment
Write-Host "Error: $($_.Exception.Message)"
exit 1
}
finally
{
# Disconnect, clean up
$session.Dispose()
}