PSParameterSets: Mandatory sometimes

I came across a situation this week where I wanted to add the option of running an existing script,  for a specific server/database combination.  The script currently has no parameters and runs against all servers in the environment from a scheduled task.  I wanted to make sure that behavior didn’t change. The other requirement was that if I specified Server, Database should be a mandatory parameter and vice versa.

The final solution was to add the two parameters to a parameter set and make them both mandatory.  I also had to add a different DefaultParameterSet (thanks to Andrew for this idea), otherwise it defaulted to the defined parameter set, meaning the script always required both Server and Database parameters.

param (
    [Parameter(Mandatory = $True, ParameterSetName='Specific')]
    [Parameter(Mandatory = $True, ParameterSetName='Specific')]

if($PSCmdlet.ParameterSetName -eq 'Normal') {
    Write-Host 'Running without params'
} else {
    Write-Host ("Server: {0}" -f $ServerName)
    Write-Host ("Database: {0}" -f $DatabaseName)

I saved the above code as params.ps1 to ensure my test cases worked. As you can see in my testing below, I can still run params.ps1 without any parameters, this replicates the current behavior of my nightly job. 

I can also now pass in Server and Database parameters, if I specify one the script will prompt for the other since they are both required.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: