PowerShell: Function to Confirm Certain Contents

It’s always a good idea to receive user confirmations prior on proceeding to making important changes. Here’s a reusable function to be added to one’s code base for that purpose.

function confirmation($content,$testValue="I confirm",$maxAttempts=3){
        write-host "Please review this content for accuracy.`r`n"
        while ($attempts -le $maxAttempts){
            if($attempts++ -ge $maxAttempts){
                write-host "A maximum number of attempts have reached. No confirmations received!`r`n"
            $userInput = Read-Host -Prompt "Please type in this value => $testValue <= to confirm. Input CANCEL to skip this item.";
            if ($userInput.ToLower() -eq $testValue.ToLower()){
                write-host "Confirmed!`r`n";
            }elseif($userInput -like 'cancel'){
                write-host 'Cancel command received.'
                write-host "Attempt number $attempts of $maxAttempts`: $userInput does not match $testValue. Try again or Input CANCEL to skip this item`r`n"
        return $confirmed;

Leave a Reply

Your email address will not be published. Required fields are marked *