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

帅比萌擦擦* 提交于 2019-12-13 06:15:19

问题


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.


回答1:


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




回答2:


I found the following solution for PowerShell V2

$sqlcmd = @(Resolve-Path "$env:ProgramFiles\Microsoft SQL Server\*\Tools\binn\SQLCMD.EXE")[0]
$path1 = 'D:\somescript.sql'
$cmdparameters = @(
    'Mandant=1',
    'SAPMandant="009"'
)

& $sqlcmd -b -S NB-BK\SQLEXPRESS -d BK_Prod -U sa -P mypassword -l 180 -i $path1 -v $cmdparameters


来源:https://stackoverflow.com/questions/12120106/how-to-bind-the-v-parameter-of-sqlcmd-from-a-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!