Thursday, July 31, 2014

Getting Started with PowerShell Modules and Advanced Functions

Jumping into PowerShell after years of Linux shell scripting can leave a person feeling a little lost. In some ways I feel that Microsoft did everyone a disservice by giving such a wide array of options to organize your code.

In Bash, for example, you basically write scripts. Scripts glue together compiled applications and other scripts. Sure you can write functions and import them by “dot sourcing” them, but that is reserved for special cases like login scripts and things like advanced screen configuration. If you want a script available everywhere, you put it in your ~/bin directory and call it a day.

When it comes to PowerShell there are so many options and conflicting ways of doing things that it can be paralyzing. One wonders why there are so many ways, what the differences are, and what is the right way. For example:

  • You can write scripts
  • You can write functions and put them in script files then, like Bash, dot source them
  • You can write .NET cmdlets, and
  • Since v2 you can write “advanced functions” (aka script cmdlets)

Then there are these things called Modules. Are modules dlls or scripts? They can be both. Finally there is the question of where these things all go and how do you get them into your session?

Now I am definitely not an expert on the subject, but this is how I view things:

  • Scripts are where you glue together command line programs and cmdlets. The output is usually text and they are usually run from the prompt (not other scripts, cmdlets, etc…)
  • Forget about writing functions and dot sourcing them
  • .NET cmdlets are program fragments that you write when you want to interact with something that only exposes a .NET api. They should be fairly stable and not something that you would want other devs on your team, or elsewhere, to modify. When you compile them into a dll, they become a module.
  • Advanced functions are program snippets that you want to glue together with scripts. This is where you write isolated reusable code. Advanced functions can be packed into a module by putting them into a text file with a .psm1 extension.

Essentially, .NET cmdlets are compiled C# code that interacts with .NET and are hard to change. Advanced functions are cmdlets written in the PowerShell programming language, predominantly interact with other PowerShell components, and are slightly easier to modify and deploy.

Next I will run through creating these things and working with them.

No comments:

Post a Comment