Мониторинг папки с помощью Powershell и сравнение ее с таблицей SQL и отправка электронного письма, если файл не существует в последние 6 часов - PullRequest
0 голосов
/ 15 января 2020

Я использую PowerShell для проверки папки, и когда файл добавляется в папку, он запрашивает таблицу sql, и если в течение последних 6 часов файл не был добавлен, он отправляет электронное письмо на адрес несколько человек сообщили им, что файл был скопирован / загружен в эту папку.

Я могу отправить электронное письмо при добавлении файла, но когда я добавил код для проверки таблицы SQL, он перестал работать. Может кто-нибудь помочь мне разобраться с остальной частью этого сценария?

[code] 
 # make sure you adjust this to point to the folder you want to monitor
$PathToMonitor = "U:\temp\test"

explorer $PathToMonitor

$FileSystemWatcher = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher.Path  = $PathToMonitor
$FileSystemWatcher.IncludeSubdirectories = $true

# make sure the watcher emits events
$FileSystemWatcher.EnableRaisingEvents = $true

# define the code that should execute when a file change is detected
$Action = {
    $details = $event.SourceEventArgs
    $Name = $details.Name
    $FullPath = $details.FullPath
    $OldFullPath = $details.OldFullPath
    $OldName = $details.OldName
    $ChangeType = $details.ChangeType
    $Timestamp = $event.TimeGenerated 
    $JustPath = Path.GetDirectoryName($FullPath)

    # SQL Work ---------------------------------------------------------------------
    $Server = 'SQL01'
    $Database = 'FTP_Upload'
    $Connection = New-Object System.Data.SQLClient.SQLConnection
    $Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;"
    $Connection.Open()
    $Command = New-Object System.Data.SQLClient.SQLCommand
    $Command.Connection = $Connection

    $text = "{0} was {1} at {2}" -f $FullPath, $ChangeType, $Timestamp

    $sql = "IF Not Exists (Select 1 From Transmit Where DateDiff(IsNull(TimeGenerated, '01/01/2020 01:00:00 PM'), '$Timestamp') < 6 ) AND PathOnly = '$JustPath' ) 
            BEGIN 
            Insert Transmit(FullPath, PathOnly, TimeGenerated)  
            Values('$FullPath', '$JustPath', '$Timestamp')
            END " 


    Write-Host ""
    Write-Host $text -ForegroundColor Green
    Write-Host $sql

    # you can also execute code based on change type here
    switch ($ChangeType)
    {
                'Created' { 
                    # Check SQL to see if there has been a file ftp'd in the last 6 hours ------ 
                    $Command.CommandText = $sql
                    $Command.ExecuteReader()
                    $Connection.Close()

                    # Send Email ---------------------------------
                    $EmailFrom = “email1@domain1.com”
                    $EmailTo = “email2@domain2.com, email3@domain3.com”
                    $Subject = “FTP Notification” 
                    $Body = $text 
                    $SMTPServer = “smtp.office365.com”
                    $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
                    $SMTPClient.EnableSsl = $true
                    $SMTPClient.Credentials = New-Object System.Net.NetworkCredential(“email1@domain1.com”, “password”);
                    $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
                    Start-Sleep -Seconds 5
                    $SMTPClient.Dispose() 

                    # this executes only when a file was renamed
                    $text = "File {0} was Created" -f $FullPath
                    Write-Host $text -ForegroundColor Yellow
                  }

        default { Write-Host $_ -ForegroundColor Red -BackgroundColor White }
    }
}

# add event handlers
$handlers = . {
    Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Changed -Action $Action -SourceIdentifier FSChange
    Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Created -Action $Action -SourceIdentifier FSCreate
    Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Deleted -Action $Action -SourceIdentifier FSDelete
    Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Renamed -Action $Action -SourceIdentifier FSRename
}

Write-Host "Watching for changes to $PathToMonitor"

try
{
    do
    {
        Wait-Event -Timeout 1
        Write-Host "." -NoNewline

    } while ($true)
}
finally
{
    # this gets executed when user presses CTRL+C
    # remove the event handlers
    Unregister-Event -SourceIdentifier FSChange
    Unregister-Event -SourceIdentifier FSCreate
    Unregister-Event -SourceIdentifier FSDelete
    Unregister-Event -SourceIdentifier FSRename
    # remove background jobs
    $handlers | Remove-Job
    # remove filesystemwatcher
    $FileSystemWatcher.EnableRaisingEvents = $false
    $FileSystemWatcher.Dispose()
    "Event Handler disabled."
}

[/code]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...