powershellout-gridview

Past only select fields to out-gridview


How can I past only a selection of fields from an object to show in out-gridview, but still keep the whole object as a result.

For example, I retrieve an object that gives me:

$listcreds = get-listofcredentials

Id                    : 03c0e0c0-0951-4698-9ba9-a70508b5467f
IsLocalProtect        : True
Name                  : vsphere.local\Administrator
CurrentUser           : False
UserName              : vsphere.local\Administrator
UserNameAtNotation    : Administrator@vsphere.local
UserNameSlashNotation : vsphere.local\Administrator
UserNameOnly          : Administrator
DomainName            : vsphere.local
EncryptedPassword     : Veeam.Backup.Common.CCodedPassword

In the gridview I want to only see Name and ID. After the user selects the row desired, I would like to have the result as the same type of object again.

When I use select-object,

$selectedcred = $listofcredentials | select-object Name, Id | out-gridview -passthru

I get the result back but I would now have to search the original object again to get the other properties of that row.

What better way to do this?


Solution

  • You need to find the full object again in the list with Where-Object

    This answer assumes the Id property is unique for every item in $listcreds

    $listcreds = get-listofcredentials
    $selectedcred = $listofcredentials | select-object Name, Id | out-gridview -passthru
    $selectedcred = $listcreds | Where-Object {$_.Id -eq $selectedcred.Id}
    

    I don't think there's a better solution here. If performance is a concern, you can convert the Where-Object into a foreach as below:

    $listcreds = get-listofcredentials
    $selectedcred = $listofcredentials | select-object Name, Id | out-gridview -passthru
    
    foreach ($cred in $listcreds) {
        if ($cred.Id -eq $selectedcred.Id) {
            $selectedcred = $cred
            break
        }
    }
    

    However, the performance difference may be negligible or even negative.