Soulless Rekkr
Soulless Rekkr

Reputation: 125

Format-Table in PowerShell inside a ForEach

Not sure what I am doing wrong here with this, I know it has to do with the fact that it is inside a ForEach loop. I have tried moving the below code around. Even with the code half and half (half in and half out of the loop does not seem to work). Still new to PowerShell and I know that I need to variables to $table each iteration or store them some where and read them later.

foreach ($gp in $GPINFO) {

    # Code that gets the values for $gp, $aclBefore and $aclAfter is here

    $table = new-object psobject -Property @{
        GPO_Name = $gp.DisplayName
        Old_Owner = $aclBefore
        New_Owner = $aclAfter
    }
    $table | Format-Table GPO_Name,Old_Owner,New_Owner
} 

If you can help me figure out what I am doing wrong that would be great, I know that every time the ForEach gets $gp out of the $GPINFO it is running the $table stuff and that is my problem. So instead of one continuous table I end up with multiple tables with one set of data in each.

Thanks in advance

Upvotes: 2

Views: 15418

Answers (2)

js2010
js2010

Reputation: 27423

You just can't pipe from foreach (). It's an odd part of the language that comes up a lot. Other ways:

Foreach-object:

$GPINFO | foreach-object {
    $gp = $_
    new-object psobject -Property @{
        GPO_Name = $gp.DisplayName
        Old_Owner = $aclBefore
        New_Owner = $aclAfter
    }
} | Format-Table GPO_Name,Old_Owner,New_Owner

Call operator and scriptblock (or $( ) but that waits until completion):

& { 
  foreach ($gp in $GPINFO) {
      new-object psobject -Property @{
          GPO_Name = $gp.DisplayName
          Old_Owner = $aclBefore
          New_Owner = $aclAfter
      }
  } 
} | Format-Table GPO_Name,Old_Owner,New_Owner

Upvotes: 8

AdminOfThings
AdminOfThings

Reputation: 25001

Just simply output the table after the loop completes.

$table = foreach ($gp in $GPINFO) {
    # Code that gets the values for $aclBefore and $aclAfter is here

    new-object psobject -Property @{
        GPO_Name = $gp.DisplayName
        Old_Owner = $aclBefore
        New_Owner = $aclAfter
    }
}
$table | Format-Table

Any output from within the foreach loop will be stored in $table. Each iteration will output an object, ultimately creating an array of those objects stored in $table.

Upvotes: 4

Related Questions