Search code examples
sqlpowershellsqlcmd

Unable to properly call sqlcmd from powershell


I had this sqlcmd snippet working in batch but when I converted to powershell, it broke. This is what I am attempting to call using powershell

Sqlcmd -S localhost\instance -d database -U username -P password -i "sqlQuery.sql" -s "," > \sqlOutput.csv -I -W -k

I tried invoke-sqlcmd but i get the error "The term 'invoke-sqlcmd' is not recognized as the name of a cmdlet, function, script file, or operable program"

In regards to the comment below, I have loaded the snapins required. This did help but I am now getting this error. "Invoke-sqlcmd : Parameter cannot be processed because the parameter name 's' is ambiguous.

If I put it in single quotes...

invoke-Sqlcmd '-S localhost\instance -d database -U username -P password -i "sqlQuery.sql" -s "," > \sqlOutput.csv -I -W -k'

I get the error "A network-related or instance-specific error occurred while establishing a connectiong to sql server. Which doesn't make sense to me as the same credentials i am using here (on the same box) work when called from batch.


Solution

  • You have to first call sqlps.exe from powershell or command prompt (assuming you have the SQL Server snap-ins for Powershell installed).

    Once you do that, execute get-help Invoke-Sqlcmd to find your way around.

    To your question, its not -S, but -ServerInstance

     PS SQLSERVER:\> Invoke-Sqlcmd -ServerInstance "srvrName" -Database "master" -Username "user123" -Password "x$34fth" 
    -InputFile "C:\Users\testUser\Desktop\test.sql" | Out-File "C:\Users\testUser\Desktop\out.txt"
    

    You can also use the MSDN documentation