Search code examples
powershellsqlcmd

How to bind the -v parameter of sqlcmd from a PowerShell


The following code, setting the -v parameter directly is working

$sqlcmd = @(Resolve-Path "$env:ProgramFiles\Microsoft SQL Server\*\Tools\binn\SQLCMD.EXE")[0]

$path1 = 'D:\somescript.sql'

& $sqlcmd -b -S NB-BK\SQLEXPRESS -d BK_Prod -U sa -P mypassword -l 180 -i $path1 -v Mandant=1 SAPMandant="009" SAPEinrichtung="0001" 

But I need a way to set these values from a PowerShell variable.

I tried:

$sqlcmd = @(Resolve-Path "$env:ProgramFiles\Microsoft SQL Server\*\Tools\binn\SQLCMD.EXE")[0]

$path1 = 'D:\somescript.sql'

$sqlcmdparameters = 'Mandant=1 SAPMandant="009" SAPEinrichtung="0001" '
& $sqlcmd -b -S NB-BK\SQLEXPRESS -d BK_Prod -U sa -P mypassword -l 180 -i $path1 -v $sqlcmdparameters

I found this on SO, but it didn't help me.


Solution

  • Try using start-process. That's what I do for Powershell command-line parsing issues. First try invoke operator (&) and if that doesn't work wrap it in a start-process call.

    $tempFile = [io.path]::GetTempFileName()
    
    $exitCode = (start-process -FilePath $sqlcmd -ArgumentList @"
    -b -S NB-BK\SQLEXPRESS -d BK_Prod -U sa -P mypassword -l 180 -i $path1 -v $sqlcmdparameters
    "@ -Wait -RedirectStandardOutput $tempFile -NoNewWindow -Passthru).ExitCode
    

    When using start-process typically you'll need to capture exitcode and also redirect output to temp file in get back the results. I'll then have some code to check $exitcode and cleanup temp file in try/catch/finally block