This Powershell script works except...

Advertisement

Yendor
Joined:
Posts:
2

This Powershell script works except...

I've kludged this together while learning to script and it works except when there are no files older than $RemovalDate. Running the script in the IDE throws no exception but when running with task scheduler, the script throws the error "You cannot call a method on a null-valued expression." and fires off the email.
I've tried excluding this exception with -ErrorAction and -ErrorVariable but neither produced the desired results.

I would like to check if there are any files older than $RemovalDate and if NOT exit otherwise continue the script and only email if there is a problem deleting old files that are actually there.

Thanks in advance for any help.

    # 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()
    }

Reply with quote

Advertisement

martin
Site Admin
martin avatar
Joined:
Posts:
29,502
Location:
Prague, Czechia

Re: This Powershell script works except...

You have to call $removeResult.Check() right after $removeResult = $session.RemoveFiles($RemovalFile)

Reply with quote

Yendor
Joined:
Posts:
2

Re: This Powershell script works except...

martin wrote:

You have to call $removeResult.Check() right after $removeResult = $session.RemoveFiles($RemovalFile)

This worked perfectly.
Thanks so much!

Reply with quote

Advertisement

You can post new topics in this forum