Create scriptblocks with expanded variables

146 Views Asked by At

I know that this question has been asked before here and here. But for one reason or another it doesn't really work for us.

Desired result

2 scriptblocks that are usable with the Pester parameter ParameterFilter whre only the variable $testTable is expanded:

{
    ($Query -like "*SELECT * FROM tableOne* 
        WHERE TicketNr IS NOT NULL AND TicketCloseDate IS NULL*")
}
{
    ($Query -like "*SELECT * FROM tableWto* 
        WHERE TicketNr IS NOT NULL AND TicketCloseDate IS NULL*")
}

The code below does not work because we need to escape everything within the $testQuery. Isn't there a way to only expand the $testTable and not the other pieces?

foreach ($testTable in @('tableOne', 'tableTwo')) {
    $testQuery = "*SELECT * FROM $testTable* 
    WHERE TicketNr IS NOT NULL AND TicketCloseDate IS NULL*"
    
    [ScriptBlock]::create("`$Query `-like $testQuery")
}
1

There are 1 best solutions below

0
On BEST ANSWER

I think I figured it out:

foreach ($testTable in @('tableOne', 'tableTwo')) {   
    [ScriptBlock]::create(@"
    (`$Query -like  "*SELECT * FROM $testTable*
    WHERE TicketNr IS NOT NULL AND TicketCloseDate IS NULL*" )
"@)
}