Author Posts

December 7, 2014 at 2:05 pm

Hello guys!

I have written a script that basically start and stops a lot different services on different servers. I have three parameters like this:

[Cmdletbinding()]
param (
[Parameter(Mandatory = $false)]
[Switch]$RestartIntranet,

[Parameter(Mandatory = $false)]
[Switch]$StopIntranet,

[Parameter(Mandatory = $false)]
[Switch]$StartIntranet
)

So my question is for the "$RestartIntranet". In that parameter how can I call the stop and start parameters?

Thanks
BR
Daniel

December 7, 2014 at 2:28 pm

That isn't how parameters work.

First, you probably want each of those to be in a different parameter set. After all, it doesn't make sense to run a command with -StopIntranet and -RestartIntranet. Using named parameter sets would make each parameter mutually exclusive.

[Parameter(ParameterSetName='RestartSet')]
[Switch]$RestartIntranet,

Second, the Mandatory=$False isn't necessary. That's the default.

Third, a parameter doesn't "call" other parameters. Your script's logic has to handle the parameters appropriately. For example:

If ($StopIntranet or $RestartIntranet) {
  # Stop here
}

If ($StartIntranet or $RestartIntranet) {
  # Start here
}

In that example, if you call -RestartIntranet, then the code would stop, and then start.

I'd actually probably argue that these should be separate commands (Restart-MyIntranet, Start-MyIntranet, Stop-MyIntranet, for example – just like Stop-Service, Start-Service, and Restart-Service). It's a bit against the usual patterns in PowerShell to see one command taking a bunch of opposing actions based on a parameter. But, if that's what you want to do, I won't complain a lot.

As more background to "how can I call the stop and start parameters," the point is that you *don't* call parameters. Parameters aren't code, they're a means of passing data (in this case, True/False values) into a command (like a script). Hope that helps.