public/Add-PSProfileCheck.ps1
|
<# .SYNOPSIS Registers the PSProfileWatcher check for the current user's profile. .DESCRIPTION Registers the PSProfileWatcher check for the current user's profile. .INPUTS None .OUTPUTS None .EXAMPLE Register-PSProfileCheck .NOTES None #> function Add-PSProfileCheck { [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')] param() <# .SYNOPSIS Adds a call to Test-PSProfileHash at the beginning of the current user's profile. .DESCRIPTION Inserts a call to Test-PSProfileHash at the very beginning of the current user's PowerShell profile so that the hash check runs before any other profile code. .INPUTS None .OUTPUTS None .EXAMPLE Add-PSProfileCheck Adds the following line to the beginning of the user's profile: `Test-PSProfileHash` .NOTES None #> # Block to insert at top of profile: import module then call the check $profileCheckBlock = "Import-Module PSProfileWatcher -ErrorAction SilentlyContinue`nTest-PSProfileHash" try { # Read the current profile content $profileContent = Get-Content -Path $profile -Raw -ErrorAction Stop } catch { Write-Error "❌ Could not read profile at '$profile'." throw $_.Exception.Message } # Check if the check (or the import+call) is already in the profile if ($profileContent -match 'Test-PSProfileHash' -or $profileContent -match 'Import-Module\s+PSProfileWatcher') { Write-Host "⚠️ Profile check or module import already exists in profile." -ForegroundColor Yellow return } # Add the import+call block to the beginning of the profile $newProfileContent = "$profileCheckBlock`n`n$profileContent" $actionTarget = "$profile" if ($PSCmdlet.ShouldProcess($actionTarget, 'Add PSProfileWatcher check')) { try { $newProfileContent | Out-File -FilePath $profile -Encoding UTF8 -Force -ErrorAction Stop Write-Host "✅ Profile check added successfully to the beginning of '$profile'." -ForegroundColor Green } catch { Write-Error "❌ Could not write profile check to file." throw $_.Exception.Message } } else { continue } } |