Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify the last item from pipeline foreach-object cmdlet

Tags:

powershell

How do I determine if process is on the last item from a pipelined ForEach-Object cmdlet?

Example: Let's say that I've previously defined connection for OLEDB to Access database to get the column definitions for each local table. I want list each of these columns with comma delimiter -- except when processing the LAST column. I want to omit the comma.

  ForEach($table in $Tables)
    { 
    $SchemaColumn = $Connection.GetSchema("Columns")
     $listarray = $schemaColumn |
     foreach-Object {

        If($_.Table_Name -eq $Table) { 

            IF "Last Item in Pipeline"   <---------------------------what would go here?
                {
                 "$($_.COLUMN_Name) $(Get-DataType($_.DATA_TYPE))"   <---- no comma!
                }
            ELSE   ## not the end of pipeline listing
                {
                 "$($_.COLUMN_Name) $(Get-DataType($_.DATA_TYPE)), "  <----yes comma!
                }
        }
     } #end Foreach-Object
like image 593
JennRobinson Avatar asked Sep 08 '14 18:09

JennRobinson


2 Answers

If you don't already have the array generated you would want to do a full construct instead of piping to foreach.

$testarray = 1..10
Foreach ($Item in $TestArray) 
{
    if ($Item -eq $testarray[-1])
    { "last item in array is $Item"}
}

To clarify, each time through the array, it checks to see if $item matches the last item in $testarray. [-1] selects last item in array

But, in your case, since you already have the array stored in $SchemaColumn you could do the same thing as I said above with the pipeline..it would look like:

if ($_ -eq $SchemaColumn[-1]) { 'stuff' }
like image 148
Noah Sparks Avatar answered Oct 13 '22 10:10

Noah Sparks


Might I suggest a different approach that doesn't rely on knowing whether it's the last item or not?

ForEach($table in $Tables)
{ 
$SchemaColumn = $Connection.GetSchema("Columns")
 $listarray = $schemaColumn |
 foreach-Object {

    If($_.Table_Name -eq $Table) { 
             "$($_.COLUMN_Name) $(Get-DataType($_.DATA_TYPE))"  # <---- no comma!
    }
 } -join ',' #end Foreach-Object

Note the last line. The result of the ForEach-Object call (all of the "no comma" results) will be joined by , characters.

If this is not what you're looking for, can you explain how you would like to use the end result?

like image 39
briantist Avatar answered Oct 13 '22 09:10

briantist