I come from a Java background, but now I'm supporting a PowerShell code base. In the PowerShell code base there are multiple modules that were written against a certain Azure environment. Now, we have another Azure environment that we need to support, and a lot of code needs to change. We don't want to fork the code base.

There are many places throughout the code where we need the equivalent of "If EnvA then do X, else if EnvB then do Y".

Coming from a Java background, I could use something like dependency injection and pass in a runtime arg that specifies the environment, then wire my dependencies based on the environment. I don't think dependency injection would work in this case, actually, from what I can tell it's not even really an option in PowerShell. Are there any PowerShell design patterns, or language agnostic design patterns, that are applicable for this type of scenario?


  • Related Dependency Injection with PowerShell
    – Doc Brown
    Nov 9, 2020 at 16:30
  • 1
    The best dependency injection analog in PowerShell (that I know of) is environment variables. You can set the process environment variables before running your scripts and the scripts look for the environment variables. Something like $Env:TARGET_ENVIRONMENT.
    – Dan Wilson
    Nov 9, 2020 at 22:11
  • @DanWilson, thanks, that seems like a better option than passing the environment context everywhere as a parameter. Nov 10, 2020 at 1:43

1 Answer 1


PowerShell is a very powerful scripting language and environment, but you really need to jump through hoops to get the same level and power that polymorphism and dependency injection can provide.

Instead, don't fight how PowerShell works — this applies to any shell scripting language. It is better to decompose your script into multiple sub scripts. Write a harness script that accepts the environment name as an argument, and delegates control to an environment specific script.

The environment specific script then calls the other scripts that execute each step of the process individually.

The "harness" script gives you a single, easy entry point, which based on the environment parameter calls a concrete script for that environment.

While you are able to use objects in PowerShell (and even initialize new objects), it is still very much a procedural execution environment. Don't fight the paradigm.

If you truly need the flexibility that object oriented programming, polymorphism and dependency injection gives you, invest the time in writing this in C#. Writing your own Cmdlet might be the better tool to use.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.