TIL you can reference PowerShell object properties using a variable containing the name
Ryan Rousseau
Posted on May 8, 2020
Song recommendation of the day
Screaming Females put on some of the best live shows I've been to.
The problem
I wrote a PowerShell script to generate markdown tables for the default permissions of Octopus Deploy's built-in user roles.
I ran into a snag matching the permissions granted to a role to their descriptions.
The object holding the descriptions looks like this:
$permissionDetails = @{
EnvironmentEdit = @{
Description = "Edit environment information"
}
EnvironmentView = @{
Description = "View environment information"
}
TeamView = @{
Description = "View team information"
}
UserView = @{
Description = "View user information"
}
}
The role has an array of permissions granted to it.
$grantedPermissions = @("TeamView", "UserView")
I need to iterate over this array and access the Description
property of the permission property that matches the name.
The solution
How to do this was a gap in my PowerShell knowledge. My first few attempts did not work at all.
After a few searches, I found this solution. You can reference a property name using a string.
$obj."SomeProp"
If you can reference it using a string, maybe you can reference it using a variable?
foreach ($name in $grantedPermissions) {
Write-Output $permissionDetails.$name.Description
}
That works!
I will definitely be using this trick in the future.
This post was originally published at blog.rousseau.dev. Cover photo by Sam Dan Truong on Unsplash.
Posted on May 8, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
May 8, 2020