O R G A N I C / F E R T I L I Z E R: Embedding Expressions in Select-Objects

Mar 29, 2015

Embedding Expressions in Select-Objects

I had my first taste of using Select-Objects in a way more than just modifying values on output or to specifically pick a set of attributes to list.

When someone asks for a list of users and their managers, meh, no big deal. When they ask for the user, their manager, and their manager’s email address -- well, no big deal but not as much of a no big deal as the first one.

I found it a bit annoying that I had to write a script to do this every time I wanted to get this type of information so I did a bit of exploring. Turned out a little while ago, while experimenting in optimizing speed in a script, I had tried a method of using Select-Object to create a custom object.

 

Using Select-Object to Pull Manager Detail on the Fly
$myData | select 
    @{n='UserId';e={$_.samaccountname}}, 
    @{n='Created';e={$_.lastlogon}}, 
    @{n='Name';e={$_.name}}, 
    @{n='Manager';e={$_.manager}},
    @{n='Manager Email';e={ 
        (get-aduser $_.manager -properties mail).mail 
        }
    }

Hopefully this makes sense. I broke it out so it’s clearer to read. For my example, I already had a dataset with specific information in it. I just needed to pipe it out and get the manager email. I piped this to export-csv to create a file to look at.

The meaningful part here is that you can embed things in the expression -- like the Get-AdUser call.

 

Slightly More Challenging
$myData | select 
    @{n='UserId';e={$_.samaccountname}}, 
    @{n='Logon';e={$_.lastlogondate}}, 
    @{n='Name';e={$_.name}}, 
    @{n='Manager';e={ 
        (get-aduser $_.samaccountname -Properties manager).manager 
        }
    }, 
    @{n='Manager Email';e={ 
        (get-aduser $(get-aduser $_.samaccountname -Properties manager).manager -properties mail).mail 
        }
    }`

And again, I broke this out but in reality ran it on a single line. In this case, I didn’t have the manager value already so I had to run a command in both expressions -- manager and manager email.

This process isn’t going to scale well with a lot of data elements. This is just to show you something that might save you a little time if you’re just tooting around. :-)