Search code examples
powershellpowershell-remotingpowershell-5.0

Powershell: Two parameter definitions for different environments?


I have a long and quite big PS5 powershell script with several parameters, defined in the param() section at the beginning of the script file. These params are strings and hashtables, including hostnames, ip addresses, domains etc.

This script runs perfectly fine in my environment, but now it should also run in a second environment where all of the parameters are different.

So without changing all of the script commands, I would want to define a second param section with different values, and provide a "switch"-variable on top of the script, something like:

param1(
... my params1 ...)

param2(
... my params2 ... )

string configToUse = "param1"

I stumbled upon powershell parameter sets, but I guess this is not what I am looking for. Also I used some node definition files (.psd1) in the past, but I want to keep everything in one file which shall just be executed by double-click without necessity of passing -param1 or -param2 on the command line.

Can someone please point me into the right direction?

thanks!


Solution

  • The param statement is only there to enable passing parameters to the script exactly as you mentioned, using the -param "value" syntax, and I would strongly recommend passing your parameters to your script in that way, instead of putting static values inside your script! It is cleaner, more robust, more transparent, more maintainable, more portable, and easier to document.

    If you still want the double-click functionality, possibly for convenience, you could for example just make a batch file that calls your script. It would just be a single line (the @ prevents the line from being printed to console):

    @powershell -File "your-script.ps1" -Param1 "value 1"
    

    You could then create seperate batch files for each of your environments.

    call-mysript-env-1.bat
    call-mysript-env-2.bat
    

    Alternatively, you could accomplish the same using shortcuts that call your script with parameters, just in the same manner.

    If, really only if, for whatever reasons, you really do not want to do this, you could just omit the param statement altogether (you're not using the functionality it was made for anyway). After all, the parameters are basically just regular variables. You could do this:

    ### start of parameters ###
    $configToUse = "param1"
    
    switch ($configToUse) {
       "param1" {
           $MyParam = "value 1"
       }
       "param2" {
           $MyParam = "value 2"
       }
    }
    #### end of parameters ###
    # rest of your script ....