Be Wary of PowerShell’s OutputType Keyword

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.

When using 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 –> [OutputType([System.String])]

String –> [OutputType('System.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 usingOutputType 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.

Adam Bertram

Chief Automator at Adam the Automator, LLC
Adam Bertram is an independent consultant, technical writer, trainer and presenter. Adam specializes in consulting and evangelizing all things IT automation mainly focused around Windows PowerShell. Adam is a Microsoft Windows PowerShell MVP, 2015 powershell.org PowerShell hero and has numerous Microsoft IT pro certifications. He authors IT pro course content for Pluralsight, is a regular contributor to numerous print and online publications and presents at various user groups and conferences.You can find Adam here on the blog or on Twitter at @adbertram.

Latest posts by Adam Bertram (see all)

2 comments

Leave a Reply