public/Remove-PSProfileCheck.ps1
|
function Remove-PSProfileCheck { [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')] param() <# .SYNOPSIS Removes the Test-PSProfileHash call from the current user's profile. .DESCRIPTION Removes the Test-PSProfileHash function call that was added to the beginning of the current user's PowerShell profile by Add-PSProfileCheck. .INPUTS None .OUTPUTS None .EXAMPLE Remove-PSProfileCheck Removes the Test-PSProfileHash call from the user's profile. .NOTES None #> # Block components to remove from the profile: import statement and the check call $importLinePattern = 'Import-Module\s+PSProfileWatcher(?:\s+-ErrorAction\s+\w+)?' $callLinePattern = 'Test-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 exists in the profile if ($profileContent -notmatch $callLinePattern -and $profileContent -notmatch $importLinePattern) { Write-Host "⚠️ Profile check does not exist in profile." -ForegroundColor Yellow return } # Remove the import line and the check call (and any immediate blank lines) # Use the pattern variables (not literal strings) when calling -replace so the regex is applied $newProfileContent = $profileContent -replace ($importLinePattern + '\r?\n?'), '' $newProfileContent = $newProfileContent -replace ($callLinePattern + '\r?\n\s*'), '' # Trim any leading blank lines that may remain after removal $newProfileContent = $newProfileContent.TrimStart("`r", "`n") $actionTarget = "$profile" if ($PSCmdlet.ShouldProcess($actionTarget, 'Remove PSProfileWatcher check')) { try { $newProfileContent | Out-File -FilePath $profile -Encoding UTF8 -Force -ErrorAction Stop Write-Host "✅ Profile check removed successfully from '$profile'." -ForegroundColor Green } catch { Write-Error "❌ Could not write to profile file." throw $_.Exception.Message } } else { continue } } |