From 2ca196af850e7a8640f85e1da97dd353da1919b8 Mon Sep 17 00:00:00 2001 From: Thibault Date: Thu, 14 Aug 2025 14:00:51 +0200 Subject: [PATCH] Add validation and ShouldProcess to PowerShell scripts --- scripts/powershell/DiskUsageReport.ps1 | 10 +++++++--- scripts/powershell/LinkCrawler.ps1 | 10 +++++++--- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/scripts/powershell/DiskUsageReport.ps1 b/scripts/powershell/DiskUsageReport.ps1 index de29107..f0f5588 100644 --- a/scripts/powershell/DiskUsageReport.ps1 +++ b/scripts/powershell/DiskUsageReport.ps1 @@ -38,13 +38,15 @@ an email if any drive has less than 10% free space. #> -[CmdletBinding()] +[CmdletBinding(SupportsShouldProcess=$true)] param( [string[]]$Volume, + [ValidateRange(1,100)] [int]$AlertThreshold = 20, [string]$CsvPath, [string]$SmtpServer, - [int]$SmtpPort = 25, + [ValidatePattern('^\d{2,5}$')] + [string]$SmtpPort = '25', [pscredential]$Credential, [switch]$UseSsl, [string]$From, @@ -84,7 +86,9 @@ foreach ($entry in $report) { $smtp = [System.Net.Mail.SmtpClient]::new($SmtpServer, $SmtpPort) if ($UseSsl) { $smtp.EnableSsl = $true } if ($Credential) { $smtp.Credentials = $Credential.GetNetworkCredential() } - $smtp.Send($mail) + if ($PSCmdlet.ShouldProcess("send alert email to $To", "Send email")) { + $smtp.Send($mail) + } } catch { Write-Error "Failed to send alert email: $_" diff --git a/scripts/powershell/LinkCrawler.ps1 b/scripts/powershell/LinkCrawler.ps1 index fcb6243..68613f1 100644 --- a/scripts/powershell/LinkCrawler.ps1 +++ b/scripts/powershell/LinkCrawler.ps1 @@ -37,7 +37,7 @@ Parallel execution requires PowerShell 7 or the ThreadJob module; otherwise URLs are tested sequentially. #> -[CmdletBinding()] +[CmdletBinding(SupportsShouldProcess=$true)] param ( [Parameter(Mandatory=$true)] [string]$BaseUrl, @@ -48,7 +48,8 @@ param ( [string]$HtmlReportPath, [string]$NotifyEmail, [string]$SmtpServer, - [int]$SmtpPort = 25, + [ValidatePattern('^\d{2,5}$')] + [string]$SmtpPort = '25', [pscredential]$Credential, [switch]$UseSsl, [switch]$ToastNotify, @@ -212,6 +213,7 @@ $($rows -join "`n") } function Send-Notifications { + [CmdletBinding(SupportsShouldProcess=$true)] param([object[]]$errors) if (-not $errors) { return } if ($NotifyEmail -and $SmtpServer) { @@ -221,7 +223,9 @@ function Send-Notifications { $smtp = [System.Net.Mail.SmtpClient]::new($SmtpServer, $SmtpPort) if ($UseSsl) { $smtp.EnableSsl = $true } if ($Credential) { $smtp.Credentials = $Credential.GetNetworkCredential() } - $smtp.Send($mail) + if ($PSCmdlet.ShouldProcess("send notification email to $NotifyEmail", "Send email")) { + $smtp.Send($mail) + } } catch { Write-Warning "Failed to send email notification: $_" } finally {