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

2 1

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay