From 638fa722f277cf93342f1baa7bfc6126988fe98a Mon Sep 17 00:00:00 2001 From: Joeri Date: Sat, 7 Feb 2026 11:32:53 +0100 Subject: [PATCH] - --- cleanup.ps1 | 178 +++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 133 insertions(+), 45 deletions(-) diff --git a/cleanup.ps1 b/cleanup.ps1 index 77e0b7e..900b161 100644 --- a/cleanup.ps1 +++ b/cleanup.ps1 @@ -11,6 +11,60 @@ # - Structured webhook logging #================================================================================ +# -------------------------------------------------------------------------------- +# Ticket Number Input +# -------------------------------------------------------------------------------- +Add-Type -AssemblyName System.Windows.Forms + +$TicketInputForm = New-Object System.Windows.Forms.Form +$TicketInputForm.Text = "Ticket Number Required" +$TicketInputForm.Size = New-Object System.Drawing.Size(400, 200) +$TicketInputForm.StartPosition = "CenterScreen" +$TicketInputForm.Topmost = $true + +$TicketLabel = New-Object System.Windows.Forms.Label +$TicketLabel.Text = "Please enter the ticket number:" +$TicketLabel.Location = New-Object System.Drawing.Point(20, 20) +$TicketLabel.Size = New-Object System.Drawing.Size(340, 20) +$TicketInputForm.Controls.Add($TicketLabel) + +$TicketTextBox = New-Object System.Windows.Forms.TextBox +$TicketTextBox.Location = New-Object System.Drawing.Point(20, 50) +$TicketTextBox.Size = New-Object System.Drawing.Size(340, 30) +$TicketInputForm.Controls.Add($TicketTextBox) + +$OKButton = New-Object System.Windows.Forms.Button +$OKButton.Location = New-Object System.Drawing.Point(100, 100) +$OKButton.Size = New-Object System.Drawing.Size(80, 30) +$OKButton.Text = "OK" +$OKButton.Add_Click({ + $script:TicketNumber = $TicketTextBox.Text + $TicketInputForm.Close() +}) +$TicketInputForm.Controls.Add($OKButton) + +$CancelButton = New-Object System.Windows.Forms.Button +$CancelButton.Location = New-Object System.Drawing.Point(200, 100) +$CancelButton.Size = New-Object System.Drawing.Size(80, 30) +$CancelButton.Text = "Cancel" +$CancelButton.Add_Click({ + $script:TicketNumber = $null + $TicketInputForm.Close() +}) +$TicketInputForm.Controls.Add($CancelButton) + +$TicketInputForm.Add_Shown({$TicketTextBox.Focus()}) +$TicketInputForm.ShowDialog() | Out-Null + +# Check if ticket number was provided +if ([string]::IsNullOrWhiteSpace($TicketNumber)) { + Write-Host "No ticket number provided. Webhook will not be sent." -ForegroundColor Yellow + $SendWebhook = $false +} else { + Write-Host "Ticket number: $TicketNumber" -ForegroundColor Green + $SendWebhook = $true +} + # -------------------------------------------------------------------------------- # Logging setup and structured data collection # -------------------------------------------------------------------------------- @@ -32,13 +86,16 @@ if (-not (Test-Path $LogDirectory)) { # Initialize structured data object $ScriptResult = [ordered]@{ "script_name" = "System Cleanup Script" - "version" = "1.2" + "version" = "1.3" + "ticket_number" = $TicketNumber + "webhook_enabled" = $SendWebhook "execution_info" = @{ "started_at" = $ScriptStartTime.ToString("yyyy-MM-dd HH:mm:ss") "computer_name" = $env:COMPUTERNAME "username" = $env:USERNAME "os_version" = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ProductName).ProductName "os_build" = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name CurrentBuild).CurrentBuild + "serial_number" = (Get-CimInstance -ClassName Win32_BIOS).SerialNumber "log_file" = $LogFile } "directory_check" = @{ @@ -89,6 +146,7 @@ $ScriptResult = [ordered]@{ "sent" = $false "status_code" = $null "error" = $null + "skipped_reason" = if (-not $SendWebhook) { "no_ticket_number" } else { $null } } "summary" = @{ "completed_at" = $null @@ -122,11 +180,27 @@ function Write-Log { "System Cleanup Script - Started at $ScriptStartTime" | Out-File -FilePath $LogFile -Append -Encoding UTF8 "Log file: $LogFile" | Out-File -FilePath $LogFile -Append -Encoding UTF8 "Computer: $($env:COMPUTERNAME)" | Out-File -FilePath $LogFile -Append -Encoding UTF8 +"Serial Number: $($ScriptResult.execution_info.serial_number)" | Out-File -FilePath $LogFile -Append -Encoding UTF8 "User: $($env:USERNAME)" | Out-File -FilePath $LogFile -Append -Encoding UTF8 +"Ticket Number: $TicketNumber" | Out-File -FilePath $LogFile -Append -Encoding UTF8 "Winget timeout: $WingetTimeout seconds" | Out-File -FilePath $LogFile -Append -Encoding UTF8 +"Webhook: $(if ($SendWebhook) { 'Enabled' } else { 'Disabled (no ticket number)' })" | Out-File -FilePath $LogFile -Append -Encoding UTF8 "================================================================================" | Out-File -FilePath $LogFile -Append -Encoding UTF8 "" | Out-File -FilePath $LogFile -Append -Encoding UTF8 +# Display startup message +Write-Host "" +Write-Host "===========================================" -ForegroundColor Cyan +Write-Host "System Cleanup Script Started" -ForegroundColor Cyan +Write-Host "Computer: $($env:COMPUTERNAME)" -ForegroundColor Cyan +Write-Host "Serial Number: $($ScriptResult.execution_info.serial_number)" -ForegroundColor Cyan +Write-Host "Ticket Number: $TicketNumber" -ForegroundColor Cyan +if (-not $SendWebhook) { + Write-Host "WARNING: No ticket number - webhook will NOT be sent!" -ForegroundColor Yellow +} +Write-Host "===========================================" -ForegroundColor Cyan +Write-Host "" + # -------------------------------------------------------------------------------- # Directory check and creation # -------------------------------------------------------------------------------- @@ -336,9 +410,6 @@ if ($ScriptResult.app_updates.winget_available) { try { Write-Log "Running winget upgrade for all applications (with timeout protection)..." -Level "INFO" - # Create temporary files for output - $WingetOutputFile = Join-Path $LogDirectory "winget_output.txt" - # Start winget process with timeout $wingetProcess = Start-Process -FilePath "winget" -ArgumentList "upgrade --all --silent --accept-package-agreements --accept-source-agreements" -NoNewWindow -Wait -PassThru -ErrorAction Stop @@ -348,10 +419,6 @@ if ($ScriptResult.app_updates.winget_available) { Write-Log "Winget exit code: $WingetExitCode" -Level "INFO" Write-Log "Winget duration: $($WingetDuration.ToString('F2')) seconds" -Level "INFO" - # Parse winget output from log file if available - $wingetOutput = Get-Content $LogFile | Select-String -Pattern "winget|Winget|Upgrading|Upgraded" -Context 2 | Out-String - $wingetOutput | Out-File -FilePath $LogFile -Append -Encoding UTF8 - # Alternative: Try to capture output directly try { $wingetOutput = winget upgrade --all --silent 2>&1 | Out-String @@ -539,49 +606,55 @@ Write-Log "Windows updates section completed." -Level "INFO" "" | Out-File -FilePath $LogFile -Append -Encoding UTF8 # -------------------------------------------------------------------------------- -# Send structured JSON to webhook +# Send structured JSON to webhook (only if ticket number was provided) # -------------------------------------------------------------------------------- Write-Log "================================================================================" -Level "INFO" Write-Log "SECTION: Webhook Notification" -Level "INFO" Write-Log "================================================================================" -Level "INFO" -try { - # Complete the summary - $ScriptEndTime = Get-Date - $ScriptResult.summary.completed_at = $ScriptEndTime.ToString("yyyy-MM-dd HH:mm:ss") - $ScriptResult.summary.total_duration_seconds = [math]::Round(($ScriptEndTime - $ScriptStartTime).TotalSeconds, 2) - - # Count errors and warnings from log file - $LogContent = Get-Content $LogFile - $ScriptResult.summary.total_errors = ($LogContent | Where-Object { $_ -match '\[ERROR\]' }).Count - $ScriptResult.summary.total_warnings = ($LogContent | Where-Object { $_ -match '\[WARNING\]' }).Count - - # Determine overall status - if ($ScriptResult.app_updates.timed_out) { - $ScriptResult.summary.overall_status = "completed_with_winget_timeout" - } elseif ($ScriptResult.summary.total_errors -gt 0) { - $ScriptResult.summary.overall_status = "completed_with_errors" - } elseif ($ScriptResult.summary.total_warnings -gt 0) { - $ScriptResult.summary.overall_status = "completed_with_warnings" - } else { - $ScriptResult.summary.overall_status = "completed_successfully" +if (-not $SendWebhook) { + Write-Log "Webhook notification SKIPPED - No ticket number provided" -Level "WARNING" + $ScriptResult.webhook.skipped_reason = "no_ticket_number" +} else { + try { + # Complete the summary + $ScriptEndTime = Get-Date + $ScriptResult.summary.completed_at = $ScriptEndTime.ToString("yyyy-MM-dd HH:mm:ss") + $ScriptResult.summary.total_duration_seconds = [math]::Round(($ScriptEndTime - $ScriptStartTime).TotalSeconds, 2) + + # Count errors and warnings from log file + $LogContent = Get-Content $LogFile + $ScriptResult.summary.total_errors = ($LogContent | Where-Object { $_ -match '\[ERROR\]' }).Count + $ScriptResult.summary.total_warnings = ($LogContent | Where-Object { $_ -match '\[WARNING\]' }).Count + + # Determine overall status + if ($ScriptResult.app_updates.timed_out) { + $ScriptResult.summary.overall_status = "completed_with_winget_timeout" + } elseif ($ScriptResult.summary.total_errors -gt 0) { + $ScriptResult.summary.overall_status = "completed_with_errors" + } elseif ($ScriptResult.summary.total_warnings -gt 0) { + $ScriptResult.summary.overall_status = "completed_with_warnings" + } else { + $ScriptResult.summary.overall_status = "completed_successfully" + } + + # Convert to JSON with proper formatting + $WebhookPayload = $ScriptResult | ConvertTo-Json -Depth 10 + + Write-Log "Sending structured JSON to webhook..." -Level "INFO" + Write-Log "Webhook URL: $WebhookUrl" -Level "INFO" + Write-Log "Ticket Number: $TicketNumber" -Level "INFO" + + # Send to webhook + $WebhookResponse = Invoke-WebRequest -Uri $WebhookUrl -Method POST -Body $WebhookPayload -ContentType "application/json" -ErrorAction Stop + + $ScriptResult.webhook.sent = $true + $ScriptResult.webhook.status_code = $WebhookResponse.StatusCode + Write-Log "Webhook notification sent successfully. Status: $($WebhookResponse.StatusCode)" -Level "INFO" + } catch { + $ScriptResult.webhook.error = $_.Exception.Message + Write-Log "Failed to send webhook notification: $($_.Exception.Message)" -Level "ERROR" } - - # Convert to JSON with proper formatting - $WebhookPayload = $ScriptResult | ConvertTo-Json -Depth 10 - - Write-Log "Sending structured JSON to webhook..." -Level "INFO" - Write-Log "Webhook URL: $WebhookUrl" -Level "INFO" - - # Send to webhook - $WebhookResponse = Invoke-WebRequest -Uri $WebhookUrl -Method POST -Body $WebhookPayload -ContentType "application/json" -ErrorAction Stop - - $ScriptResult.webhook.sent = $true - $ScriptResult.webhook.status_code = $WebhookResponse.StatusCode - Write-Log "Webhook notification sent successfully. Status: $($WebhookResponse.StatusCode)" -Level "INFO" -} catch { - $ScriptResult.webhook.error = $_.Exception.Message - Write-Log "Failed to send webhook notification: $($_.Exception.Message)" -Level "ERROR" } Write-Log "Webhook section completed." -Level "INFO" @@ -598,6 +671,12 @@ Write-Log "Duration: $($ScriptResult.summary.total_duration_seconds) seconds" -L Write-Log "Overall Status: $($ScriptResult.summary.overall_status)" -Level "INFO" Write-Log "Total Errors: $($ScriptResult.summary.total_errors)" -Level "INFO" Write-Log "Total Warnings: $($ScriptResult.summary.total_warnings)" -Level "INFO" +Write-Log "Serial Number: $($ScriptResult.execution_info.serial_number)" -Level "INFO" +Write-Log "Ticket Number: $TicketNumber" -Level "INFO" +Write-Log "Webhook Sent: $(if ($ScriptResult.webhook.sent) { 'Yes' } else { 'No' })" -Level "INFO" +if (-not $ScriptResult.webhook.sent -and $ScriptResult.webhook.skipped_reason) { + Write-Log "Webhook Skipped Reason: $($ScriptResult.webhook.skipped_reason)" -Level "INFO" +} Write-Log "Log File: $LogFile" -Level "INFO" Write-Log "================================================================================" -Level "INFO" Write-Log "System Cleanup Script Completed" -Level "INFO" @@ -610,10 +689,19 @@ Write-Host "===========================================" -ForegroundColor Green Write-Host "Script completed successfully!" -ForegroundColor Green Write-Host "Duration: $($ScriptResult.summary.total_duration_seconds) seconds" -ForegroundColor Green Write-Host "Status: $($ScriptResult.summary.overall_status)" -ForegroundColor Green +Write-Host "Serial Number: $($ScriptResult.execution_info.serial_number)" -ForegroundColor Cyan +Write-Host "Ticket Number: $TicketNumber" -ForegroundColor Cyan Write-Host "Errors: $($ScriptResult.summary.total_errors)" -ForegroundColor $(if ($ScriptResult.summary.total_errors -gt 0) { "Red" } else { "Green" }) Write-Host "Warnings: $($ScriptResult.summary.total_warnings)" -ForegroundColor $(if ($ScriptResult.summary.total_warnings -gt 0) { "Yellow" } else { "Green" }) if ($ScriptResult.app_updates.timed_out) { Write-Host "Winget timed out after $WingetTimeout seconds" -ForegroundColor Yellow } +if (-not $SendWebhook) { + Write-Host "Webhook: NOT SENT (no ticket number)" -ForegroundColor Yellow +} elseif ($ScriptResult.webhook.sent) { + Write-Host "Webhook: SENT successfully (Status: $($ScriptResult.webhook.status_code))" -ForegroundColor Green +} else { + Write-Host "Webhook: FAILED to send" -ForegroundColor Red +} Write-Host "Log file: $LogFile" -ForegroundColor Cyan Write-Host "===========================================" -ForegroundColor Green \ No newline at end of file