DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for TIL you can reference PowerShell object properties using a variable containing the name
Ryan Rousseau for Octopus Deploy

Posted on • Originally published at blog.rousseau.dev

TIL you can reference PowerShell object properties using a variable containing the name

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.

Top comments (0)

Regex for lazy developers

regex for lazy devs

You know who you are. Sorry for the callout πŸ˜†