Using a custom model class for your SPE report scripts can clean them up and make it easier to control the action button visibility.
When writing the scripts shown in my previous post about Commerce Staging, I kind of stumbled upon a technique that I rather like for working with SPE report scripts. In my first pass at the scripts, I was sending strings in an array through the pipeline to
Show-ListView and using expressions in the property list to get some additional data related to those strings. It looked something like this.
This works, but it’s not the very easy to read. The bigger problem that I found was when I wanted to add an action to this ListView report. The script library containing the action scripts have to be named after the type of the objects that are passed to
Show-ListView. That means I would need to name my script library item
string in this case. Additionally, any other script that passed strings to
Show-ListView would also potentially show my action button.
One way to deal with the visibility issue is to use the
Show Rule field to add conditions that must be true for the rule to show. While that works perfectly well, it seemed to me like there should be an easier way to deal with the problem. I knew that you could create custom objects in powershell, but they were always essentially anonymous types. I wanted to have a type that I could name myself to ensure it was unique to this particular script. It turns out that PowerShell 5 makes this super easy. You can just define your own class.
After defining your class, you can rewrite the script more like this.
It may be a matter of preference, but I think that this is easier to read. Additionally, if you define your class in a function script as I did, it can be imported into several other scripts, including the action scripts. The icing on the cake was that I could now name the script library for my actions
StagingProject. There is very little chance that someone else is going to pass objects of that type name to their ListView, so I don’t need to add conditions to the
Show Rule field any longer.
The next time you write a PowerShell report using
Show-ListView, rather than passing in
Item objects or some other common type, consider creating a custom model class like this. You’ll be happy you did.