PowerShell - Delete Emails from folders by X numbers of days

Delete Emails from folders by X numbers of days


# SQL connection
$conn = new-object "System.data.sqlclient.SQLconnection"
$con.ConnectionString =(“Data Source=localhost;Initial Catalog=EmailDW;Integrated Security=SSPI”)
$conn.open()
 
$sqlcmd = new-object "System.data.sqlclient.sqlcommand"
$sqlcmd.connection = $conn
$sqlcmd.CommandTimeout = 600000
 
# Outlook Connection
$Outlook = New-Object -ComObject Outlook.Application
# Outlook folder to clean up and load into SQL
$EmailsInFolder = $Outlook.Session.Folders.Item(2).Folders.Item("Inbox").Folders.Item("SPAM Mail").Items
 
# Get todays date
$Today = get-date
 
foreach ($email in $EmailsInFolder)
    {
         
          IF ($now-$Email.SentOn -ge 30.)
              {
                ## build results
                $sent = $email.SentOn
                $sub = $email.Subject
                $sender = $email.SenderName
                $to = $email.To
                $sen = $email.Sensitivity
 
                $query = "INSERT INTO dbo.EmailLog ( emailSentOn , emailSubject , emailSenderName , emailTo , emailSensitivity ) VALUES  ( '$sent', '$sub', '$sender', '$to' , '$sen') ”
                #write-host $query
                $sqlcmd.CommandText = $query
                $rowsAffected = $sqlcmd.ExecuteNonQuery()
                $email.Delete()
 
              }
         
 
    }