1

I have a custom PS Object that is something like the below:

ID                           Folder
MyServer01                   \\Server\Share\Share\MyServer01
MyServer02                   \\Server\Share\Share\MyServer02

Naturally the object itself is rather large, with over 1000 entries. I need to be able to select a specific row of the object based on querying the ID.

I thought something like this would work but I'm not having much luck:

$obj | Select-Object | Where-Object ($_.ID -eq "MyServer01")

I need it to return the entire row, so the above (assuming it worked) would return:

MyServer01                   \\Server\Share\Share\MyServer01

EDIT:

foreach ($mf in $Folders.Tables[0]) {
    $Info = New-Object System.Object
    $Info | Add-Member -Type NoteProperty -Name ID -Value $mf.ID
    $Info | Add-Member -Type NoteProperty -Name Folder -Value $mf.Folder
    $obj += $Info
}
14
  • Select-Object is unnecessary/redundant. What do you mean by "I'm not having much luck"? What happens? Commented Jan 17, 2016 at 12:53
  • I get no results returned. Commented Jan 17, 2016 at 13:28
  • Can you show us where $obj comes from? How it's assigned/created? Commented Jan 17, 2016 at 13:31
  • See edit. The $managedFolders.Tables[0] is a SQL table. Commented Jan 17, 2016 at 13:33
  • 1
    In that case your Where-Object filter should be just fine. Only thing that could mess with it is if the ID has trailing whitespace (ie "MyServer01 "). Try with -match "MyServer01" or -like "*MyServer01*" Commented Jan 17, 2016 at 13:35

1 Answer 1

3

Use a hashtable for storing your objects:

$obj = @{}
foreach ($mf in $Folders.Tables[0]) {
    $Info = New-Object -Type System.Object
    $Info | Add-Member -Type NoteProperty -Name ID -Value $mf.ID
    $Info | Add-Member -Type NoteProperty -Name Folder -Value $mf.Folder
    $obj[$mf.ID] = $Info
}

Don't append to an array in a loop, as that tends to perform poorly.

If your code doesn't depend on the objects being created explicitly as System.Object I'd also recommend to create them as custom objects:

$obj = @{}
foreach ($mf in $Folders.Tables[0]) {
    $Info = New-Object -Type PSCustomObject -Property @{
      'ID'     = $mf.ID
      'Folder' = $mf.Folder
    }
    $obj[$mf.ID] = $Info
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for New-Object -Property @{} over Add-Member, but the real overhead comes from continually resizing the array with +=. Assigning the entire foreach loop directly to the array variable ($obj = foreach(){}) will exhibit the same performance improvement as with a hashtable, with the added advantage that you don't need a distinct identifier per object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.