How to execute sqlcmd from powershell?

前端 未结 7 1492
忘掉有多难
忘掉有多难 2020-12-29 05:11

I have a string in powershell, which contains a native sqlcmd command. The command itself can be executed successfully in cmd.exe. I have difficulty in executing them in pow

7条回答
  •  粉色の甜心
    2020-12-29 06:09

    This is how I build some externals command in my scripts

    $scriptblock = {fullpath\sqlcmd -S `"(local)\instance1`" <# comment option -S #>`
                                    -U a `
                                    -P a `
                                    -i `"c:\temp\sql.sql`" }
    Invoke-Command -ScriptBlock $scriptBlock
    

    You can then use $args variable inside it and even start it remotly.

    $scriptblock = {fullpath\sqlcmd -S `"(local)\instance1`" <# comment option -S #>`
                                    -U a `
                                    -P a `
                                    -i `"$($args[0])`" }
    Invoke-Command -ScriptBlock $scriptBlock -argumentList "c:\temp\sql.sql" -computer "remote1"
    

    Remark :

    This allow to comment each param.

    Be careful not to forget a "`" and no space after them where they are at the end of the line.

提交回复
热议问题