Whenever creating an advanced function in PowerShell, it’s always a good idea to define what type of object the function will return by using the
OutputType keyword. I wrote a little article about this awhile back if you’re unfamiliar with the concept.
OutputType is a great way to show what type of object the function returns as well as assisting in tab-completion as you can read from the link. However, I’ve noticed an issue that’s tripped me up twice now and thought I’d write something on it.
OutputType, you’ve got a couple different ways to define the object type. You can either define the expressed object type or define the object type in a string.
- .NET Type –>
- String –>
For ages, I always preferred to use the .NET type because I thought it was more explicit however I’ve been burned twice now and have started using the string. Why? Let me explain.
Whenever this function is declared (not invoked) and you define the
OutputType as the actual .NET type, the function attempts to resolve this immediately. I’ve noticed this the most when the function is part of a module when the module is imported. The function doesn’t even need to run. This usually isn’t a problem if you’re defining built-in types like strings, integers, what have you. The problem arises when you’re working with custom object types that are part of assemblies that don’t come installed by default.
I’m so used to working on my local machine with all of the assemblies, I’ll share my code and then wonder why a simple module import won’t work on someone else’s machine. The error that it provides is not intuitive at all.
So, next time you’re using
OutputType use the string instead of the actual type. You’ll get the same results yet not force the type to be evaluated at module import time. Instead, move your assembly checks into your own error handling routine instead.