Is there a "template-sort-of-thing" in powershell?

I have a code like this that is repeated multiple times in each of my conditional statements/cases. i have 3 conditions…for now, and everything works perfectly, but im mulling reformatting the script for easier reading.

One of the ways ive thought is to make a function, but the problem is that, i have a while loop that is intended for a specific scenario in each conditional statement that dequeues from a Queue containing some column names from a file.

so based on the code below that i want to put in some sort of template, i cant think of how this could work because as you can see, $tb stands for $table, which is what im opening prior to the conditional statements in my code. if i were to include everything regarding the server connection and table in a function, that means when i pass the “function” containing the code to the while loops, it will be creating/instantiating the table every iteration, which wont make sense and wont work anyways.

so i am thinking of using something like annotations, something like a template which wont expect to return anything or need reasonable arguments like a function otherwise would. The question is, does something like that exist?

This is the code that is the same across all my while loops that i would like to “store” somewhere and just pass it to them:

$dqHeader = $csvFileHeadersQueue.Dequeue()

$column = New-Object Microsoft.SqlServer.Management.Smo.Column($tb, $dqHeader, $DataType1)

if ($dqHeader -in $PrimaryKeys)
{
    # We require a primary key.

    $column.Nullable = $false
    #$column.Identity = $true #not needed with VarChar
    #$column.IdentitySeed = 1 #not needed with VarChar
    $tb.Columns.Add($column)

    $primaryKey = New-Object Microsoft.SqlServer.Management.Smo.Index($tb, "PK_$csvFileBaseName")
    $primaryKey.IndexType = [Microsoft.SqlServer.Management.Smo.IndexType]::ClusteredIndex
    $primaryKey.IndexKeyType = [Microsoft.SqlServer.Management.Smo.IndexKeyType]::DriPrimaryKey #Referential Integrity to prevent data inconsistency. Changes in primary keys must be updated in foreign keys.
    $primaryKey.IndexedColumns.Add((New-Object Microsoft.SqlServer.Management.Smo.IndexedColumn($primaryKey, $dqHeader)))
    $tb.Indexes.Add($primaryKey)
}
else
{
    $tb.Columns.Add($column)
}

think of it like a puzzle piece that would fit right in when requested to do so in the while loops to complete that “puzzle”

related

As mentioned here powershell - Is there a "function-like-thing" that can act as a template? - Stack Overflow I recommend you use a helper function…

[quote quote=225195]As mentioned here https://stackoverflow.com/questions/61569760/is-there-a-function-like-thing-that-can-act-as-a-template I recommend you use a helper function…

[/quote]
i went with your recommendation, thanks :slight_smile: