# This script depends on the host, port, username, and password being defined in the calling script
If ( -not($SFTPHost) ) { Write-Error "SFTP host is not defined, this script will exit." ; Exit }
If ( -not($SFTPPort) ) { Write-Error "SFTP port is not defined, this script will exit." ; Exit }
If ( -not($SFTPUser) ) { Write-Error "SFTP username is not defined, this script will exit." ; Exit }
If ( -not($SFTPPass) ) { Write-Error "SFTP password is not defined, this script will exit." ; Exit }

$ExportedEvents = "${Env:TEMP}\${Env:COMPUTERNAME}_events.csv"

# Install Posh-SSH module
If ( !(Get-Module -ListAvailable -Name Posh-SSH) ) {
    Write-Output "Installing Posh-SSH module"
    Install-Module -Name Posh-SSH -Force
}

# Cleanup previous runs
If ( Test-Path $ExportedEvents ) {
    Write-Output "Deleting exported events from previous script run ""${ExportedEvents}"""
    Try { Remove-Item $ExportedEvents -Force -ErrorAction Stop }
    Catch { Write-Output "Cannot remove files from previous script execution. This script cannot run." ; Exit }
}

# Get all available log files
$Logs = Get-WinEvent -ListLog *

# Export all significant events from all available log files
ForEach ($Log in $Logs) {
    $LogName = $Log.LogName
    Write-Output "Exporting events from: ${LogName}"
    Try { Get-WinEvent -LogName $LogName -FilterXPath "Event/System[Level=1 or Level=2 or Level=3]" -ErrorAction Stop | Select-Object LogName,ProviderName,Level,Id,Message | Export-Csv -Path "${ExportedEvents}" -Append -NoTypeInformation -ErrorAction Stop }
    Catch { Write-Error $_.Exception.Message }
}

# Deduplicate exported events
Write-Output "Deduplicating and sorting all exported events"
Try {
    $TempEvents = Import-Csv $ExportedEvents -ErrorAction Stop | Sort-Object LogName,ProviderName,Id -Unique
    $TempEvents | Sort-Object -Property LogName,ProviderName | Export-Csv $ExportedEvents -NoTypeInformation -ErrorAction Stop
}
Catch { Write-Error $_.Exception.Message }

# Upload to SFTP site
If ( Test-Path $ExportedEvents ) {
    $SFTPCred = New-Object System.Management.Automation.PSCredential($SFTPUser,$SFTPPass)
    
    # Wait for a random amount of time before starting the connection and uploading
    Start-Sleep -Seconds $(Get-Random -Minimum 1 -Maximum 120)

    # Make the connection and upload the file
    $SFTPSession = New-SFTPSession -ComputerName $SFTPHost -Credential $SFTPCred -AcceptKey -Port $SFTPPort
    Write-Output "Uploading events to SFTP site"
    Try { Set-SFTPItem -SessionId $SFTPSession.SessionId -Path $ExportedEvents -Destination . -Force }
    Catch { Write-Error $_.Exception.Message }
    Finally { Remove-SFTPSession -SessionId $SFTPSession.SessionId }
    
}

# Cleanup
Write-Output "Deleting ""${ExportedEvents}"""
Remove-Item $ExportedEvents -Force -ErrorAction SilentlyContinue