Unable to properly call sqlcmd from powershell - sql

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.

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

Goto
Windows Explorer 
Right Click Computer 
Properties 
Advanced System Settings 
Environment Variables
Make sure PSModulePath is set with following string.
C:\Program Files (x86)\Microsoft SQL Server\110\Tools\PowerShell\Modules

Related

Restore a postgres backup file using the command line\shell in Win10

I can't restore backup, I'm using this query:
psql -h <localhost> -U <Username> -d <Name_of_database> -f <Name_of_disk:\name of backup file.sql>
In case when I type this query in CommandLine I have message:"'psql' is not recognized as an internal or external command" and all is stopped.
In case when I type this query in SQLShell I have message : "Invalid command (there stored part of path to backup.sql). Try \? for help." and all is stopped.

Append output of sqlcmd to file using Job Agent

After some research I found the solution to append the output of a sqlcmd command to a csv file. Everything is fine when using the Command Shell:
C:\temp>sqlcmd -S <SERVER> -d <DATABASE> -E -Q "SELECT [something] FROM [TableX] WHERE [columnY] IS NOT NULL;" -W -h-1 -s";" >>"<FULL_PATH_TO_CSV-FILE>"
I want to schedule this stuff by using SQL Server Job Agent (with same account as with console) so I add a Job (type CmdExec). Job execution fails with the following error (unexpected argument):
Meldung
Ausgeführt als Benutzer: ''[ACCOUNT]''. Sqlcmd: '>>''[FULL_PATH_TO_CSV-FILE]'': Unerwartetes Argument. Geben Sie '-?' ein, um die Hilfe anzuzeigen. Prozessexitcode 1. Fehler bei Schritt.
My workaround works fine: remove >>"<FULL_PATH_TO_CSV-FILE>" and use the output file of the step. But: I want to use the output file for logging purposes - not for the data output ...
The question is: why does the ">>" command does not work within a SQL Server Agent job?
I don't want to simply redirect the output. I know that sqlcmd provides the parameter -o for that. In this case an existing file would be overwritten. That's not what I want.
Unfortunatelly I do not have the reputation to post the screenshots so far.
Thanks you very much in advance!
Best regards,
D.C.
I think the issue here that SQL server agent creates process "sqlcmd" and sends this whole line to it as a parameters. So "sqlcmd" doesn't know what this means - ">>..." and returns with error.
To use this (">>") Command Shell syntax you should call it in the SQL agent. So try:
cmd.exe /c "sqlcmd -S -d -E -Q "SELECT [something] FROM [TableX] WHERE [columnY] IS NOT NULL;" -W -h-1 -s";" >>"""

Need help to make sqlcmd run as per requirements

I wanted to run SQLCMD.EXE as mentioned here - http://blog.daringa.com/archives/tag/error-hresult-e_fail-has-been-returned-from-a-call-to-a-com-component
I used the line in link with proper path to sqlcmd, user and password I use to login to my SQL server - sqlcmd -S .\MYSQLSERVER2008 -U MyUsername -P MyPassword -i C:\Database\hugescript.sql
Problem - I see a window and some message, but it vanishes so quickly that I cannot even see what it is. How do I see this window and how do I then execute an SQL file via SQLCMD.EXE
Why am I executing a script via SQLCMD and not SQL SERVER (ie SS) MGMT STUDIO ?
SS throws an error when sql files are big, ie about 100mb or more.
You can redirect the output from sqlcmd
sqlcmd -S .\MYSQLSERVER2008 -U MyUsername -P MyPassword
-i C:\Database\hugescript.sql > log.txt 2> error.txt
It will write the output to log.txt file and errors to error.txt file (you can specify the full path if you want). You can then see what's happening.

Execute remote powershell script from local system

I am new to this powershell..Execuse me if anything wrong here.
Now coming straight to the question I have a powershell script stored in one of the drive say "D:\myfile.ps1" which is in remote system.
Now I need to execute this script from my local system and this is the way I have done
ExecuteCommand(Directory.GetCurrentDirectory & "\Psexec \\myservername -i -u username -p password powershell.exe Invoke-Command -ComputerName \\myservername -FilePath D:\myscript.ps1")
The result is showing me this way without any output giving me an error
"powershell exited on myservername with error code 1'
And If run this script to run .exe on the same server it's working fine
ExecuteCommand(Directory.GetCurrentDirectory & "\psexec \\myservername -u username -p password D:\myfile.exe")
So what's the correct way to execute my script to run on remote desktop ?
Update after suggestions:
Can you just try :
ExecuteCommand(Directory.GetCurrentDirectory & "\Psexec \\myservername -i -u username -p password powershell.exe -command "&{Invoke-Command -ComputerName \\myservername -FilePath D:\myscript.ps1}"

Cannot execute script: Insufficient memory to continue the execution of the program

I have a 123MB sql file which I need to execute in my local PC. But I am getting
Cannot execute script: Insufficient memory to continue the execution of the program
How to solve this issue?
use the command-line tool SQLCMD which is much leaner on memory. It is as simple as:
SQLCMD -d <database-name> -i filename.sql
You need valid credentials to access your SQL Server instance or even to access a database
Taken from here.
It might help you! Please see below steps.
sqlcmd -S server-name -d database-name -i script.sql
Open cmd.exe as Administrator.
Create Documents directory.
Put your SQL Script file(script.sql) in the documents folder.
Type query with sqlcmd, server-name, database-name and script-file-name as like above highlighted query or below command line screen.
For Windows Authentication use this sql cmd
SQLCMD -S TestSQLServer\SQLEXPRESS -d AdventureWorks2018 -i "d:\document\sql document\script.sql"
Note: If there is any space in the sql file path then use " (Quotation marks) "
For SQL Server Authentication use this sql cmd
SQLCMD -S TestSQLServer\SQLEXPRESS -U sa -P sasa -d AdventureWorks2018 -i "d:\document\sql document\script.sql"
-S TestSQLServer\SQLEXPRESS: Here specify SQL Server Name
-U sa: Username (in case of SQL Server Authentication)
-P sasa: Password (in case of SQL Server Authentication)
-d AdventureWorks2018: Database Name come here
-i "d:\document\sql document\script.sql": File Path of SQLFile
You can also simply increase the Minimum memory per query value in server properties. To edit this setting, right click on server name and select Properties > Memory tab.
I encountered this error trying to execute a 30MB SQL script in SSMS 2012. After increasing the value from 1024MB to 2048MB I was able to run the script.
(This is the same answer I provided here)
My database was larger than 500mb, I then used the following
C:\Windows>sqlcmd -S SERVERNAME -U USERNAME -P PASSWORD -d DATABASE -i C:\FILE.sql
It loaded everything including SP's
*NB: Run the cmd as Administrator
If I understand your problem correctly, you are trying to restore (transact sql) xyz.sql - database + schema. You can try this command which worked for me:
SQLCMD -U sa -i xyz.sql
Try this step,
1)Open PowerShell
2)Write this command:
sqlcmd -S PCNAME\SQLEXPRESS -U user -P password -d databanse_name -i C:\script.sql
3)Press Return
:-)
Below script works perfectly:
sqlcmd -s Server_name -d Database_name -E -i c:\Temp\Recovery_script.sql -x
Symptoms:
When executing a recovery script with sqlcmd utility, the ‘Sqlcmd: Error: Syntax error at line XYZ near command ‘X’ in file ‘file_name.sql’.’ error is encountered.
Cause:
This is a sqlcmd utility limitation. If the SQL script contains dollar sign ($) in any form, the utility is unable to properly execute the script, since it is substituting all variables automatically by default.
Resolution:
In order to execute script that has a dollar ($) sign in any form, it is necessary to add “-x” parameter to the command line.
e.g.
Original:
sqlcmd -s Server_name -d Database_name -E -i c:\Temp\Recovery_script.sql
Fixed:
sqlcmd -s Server_name -d Database_name -E -i c:\Temp\Recovery_script.sql -x
Sometimes, due to the heavy size of the script and data, we encounter this type of error. Server needs sufficient memory to execute and give the result. We can simply increase the memory size, per query.
You just need to go to the sql server properties > Memory tab (left side)> Now set the maximum memory limit you want to add.
Also, there is an option at the top, "Results to text", which consume less memory as compare to option "Results to grid", we can also go for Result to Text for less memory execution.
sqlcmd -S mamxxxxxmu\sqlserverr -U sa -P x1123 -d QLDB -i D:\qldbscript.sql
Open command prompt in run as administrator
enter above command
"mamxxxxxmu" is computer name
"sqlserverr" is server name
"sa" is username of server
"x1123" is password of server
"QLDB" is database name
"D:\qldbscript.sql" is sql script file to execute in database
If you need to connect to LocalDB during development, you can use:
sqlcmd -S "(localdb)\MSSQLLocalDB" -d dbname -i file.sql
As in most answers given here use the command-line tool. In my case the script already has database creation code. If your script contains CREATE DATABASE command, for example
USE [master]
GO
CREATE DATABASE [your-database-name]
Then do not use the -d your-database-name, instead use the following command.
For Windows Authentication use the command
sqlcmd -S ServerName\InstanceName -i "script.sql" -x
For SQL Server Authentication use the command
sqlcmd -S ServerName\InstanceName -U usename -P password -i "script.sql" -x