Reading dotnet class properties in a Sitecore Powershell script
Recently I was working on a Sitecore Powershell report generator that allows the end user to select the columns that they need to be returned in a CSV file. After the user selects the columns, the report generates the CSV according to the parameters. Below is an example of the classes and PSE script that supports this.
The report class used to populate the columns looks like this…
We’re using the CsvHelper nuget package to generate the CSV, which allows us to ignore properties that we don’t want. I won’t post the code here, but it creates a map and uses .Ignore() on the columns that we don’t want.
Now to the powershell script in Sitecore…
This works well enough for the few columns in this demo, but you will have noticed that we have to repeat ourselves with the column names in both the POCO and the PSE script. During the lifetime of this solution, undoubtedly there will be more columns added or removed and that raises a couple of problems:
- We need to update the property names in several places (property name in the POCO, property name and pretty name in the PSE script), and if the next developer working on it is not familiar with the code, it will take them longer to make changes.
- We need to update and commit the serialized item containing the PSE report every time there is a change. (Of course, your CI/CD pipeline automatically runs unicorn, so it’s no problem…. right? ;-p )
The solution
Ideally we would be better to enumerate the property names in the POCO from Powershell, so that we don’t need to repeat ourselves. But is it possible to:
- Read the DLL within Sitecore Powershell.
- Get the class.
- Read the class properties.
- Put them into a hashtable.
It turns out that the answer to all four is YES!
As shown below, we can keep the property name and pretty field name together using a custom attribute on each property.
And now we don’t have to explicitly list the columns in the PSE script…
Conclusion
By using Powershell’s DotNet integration, we can read information dynamically from code, improving code maintainability and reliability, and reducing the number of changes that need to be deployed.
I hope this has been helpful. Thanks for reading. :-)