How to execute sqlcmd from powershell?

前端 未结 7 1487
忘掉有多难
忘掉有多难 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 05:51

    Both instance name and username should be fully qualified

    <domain_name>\Instanc_name and <domai_name>\Username. Only your instance name is correctly scripted.

    0 讨论(0)
  • 2020-12-29 06:03

    Use Invoke-Expression rather than Invoke-Command

    0 讨论(0)
  • 2020-12-29 06:08

    This is what worked for me for using sqlcmd from within the powershell script using the & operator, see sample to generate a csv file:

    & cmd /c "sqlcmd -S $sv -i $PROCFILE -s, -v varDB = $dbclean -o $filename"

    $sv has server name like SERVERNAME\INSTANCE

    $PROCFILE is like d:\TSTSQL\Sqlquery.SQL

    $filename is d:\TSTSQL\Desiredoutfilename.CSV

    $dbclean is a parameter passed to the sql file

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-29 06:10

    To call a Win32 executable you want to use the call operator & like this:

    & sqlcmd -S "(local)\instance1" -U a -P a -i "c:\temp\sql.sql"
    
    0 讨论(0)
  • 2020-12-29 06:10

    The first positional parameter of invoke-command is -scriptblock, and it expects a script block argument. To take advantage of a here-string to build the command and then run it with invoke-command, you need to convert the here-string to a script block:

    $sql = @"
    sqlcmd -S "(local)\instance1" -U a -P a -i "c:\temp\sql.sql"
     "@
    
     Invoke-Command ([scriptblock]::create($sql))
    
    0 讨论(0)
提交回复
热议问题