Ensure a Function Should be Invoked

it’s been a long time since I’ve written; I know.

I still use PowerShell at every opportunity; I just don’t write about it like I used to. An average of a post per week for nine years, which is what I managed previously, wasn’t always something I planned to maintain. I probably did, but yeah, here we are.

I wrote a long-running function recently, as it inspects every Active Directory (AD) group or user. As a precaution, I added a couple of warning messages to the start of the invocation. In addition, I added a Read-Host prompt. Ugh, I know, a host-based command… in a function.

So after this, I changed it, which we’ll discuss in a moment.

Write-Warning -Message "This function will run against all the $($ObjectType)s in Active Directory." -WarningAction Continue
Write-Warning -Message 'There is a high probability this will take a lengthy time to complete. '-WarningAction Continue
$Response = Read-Host -Prompt 'Do you want to continue? (y/n)'

if ($Response -eq 'y') {...}

In addition to the ObjectType parameter, I added a Force parameter to the Param statement.

    [CmdletBinding()]
    Param (
          [Parameter(Mandatory, HelpMessage = "Please either enter 'Group' or 'User' for this parameter argument.")]
          [ValidateSet('Group','User')]
          [string]$ObjectType,

          [Parameter()]
          [switch]$Force
    ) # end Param.

Then in the body of the function, I check that the parameter has been included. If it’s not, the user receives the warning messages, to include a new one, indicating to use the Force parameter. If the parameter is included, all is well, and the remainder of the function is invoked.

if (-not($Force)) {
    Write-Warning -Message "This function will run against all the $($ObjectType)s in Active Directory." -WarningAction Continue
    Write-Warning -Message 'There is a high probability this will take a lenghty time to complete. '-WarningAction Continue
    Write-Warning -Message 'Please invoke the function again with the Force parameter as confirmation of invocation.'
} else {
    Write-Output -InputObject 'The Force parameter was included; carry on.'
} # end if-else.