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
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' }
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With