Cannot connect to dockerized SQL Server using invoke-sqlcmd - sql-server

I don't have sqlcmd.exe nor sqlps for some bizarre reason, even though I installed the sqlserver module from PSGallery, so I'm not sure if that's screwing me over or not.
The main problem I have is that I just can't seem to be able to SQL Server using invoke-sqlcmd, even though I was able to connect to it with SSMS.
This is the SQL Server container:
e1cfd6032947 mcr.microsoft.com/mssql/server:2019-latest "/opt/mssql/bin/perm…" 21 hours ago Up 21 hours 0.0.0.0:1433->1433/tcp, :::1433->1433/tcp mystifying_keller
I connected to it through SSMS, but for some reason it just doesn't work through powershell 5 with invoke-sqlcmd applet, the annoying thing is that it doesn't even give me an error:
PS C:\> Invoke-Sqlcmd -ServerInstance 127.0.0.1:1433 -Database db1
PS C:\> Invoke-Sqlcmd -ServerInstance '127.0.0.1:1433' -Database db1
PS C:\> Invoke-Sqlcmd -ServerInstance '127.0.0.1,1433' -Database db1
PS C:\> Invoke-Sqlcmd -ServerInstance '127.0.0.1,1433' -Database db1 -Username 'SA' -Password 'yourStrong(!)Password'
PS C:\> Invoke-Sqlcmd -ServerInstance '127.0.0.1,1433' -Database db1 -Username 'SA' -Password 'yourStrong(!)Password' -Query "PRINT 'This is output'"
PS C:\> Invoke-Sqlcmd -ServerInstance '127.0.0.1,1433' -Database db1 -Username 'SA' -Password 'yourStrong(!)Password' -Query "SELECT * FROM Users;"
PS C:\>
(Yes, db1 is a test db that I created in SSMS just in case a database is actually necessary).
I have literally no clue what I'm doing wrong, or why it's not working :/

The table I tried doing this to was empty, hence no results returned:
PS C:\> Invoke-Sqlcmd -ServerInstance '127.0.0.1,1433' -Database db1 -Username 'SA' -Password 'yourStrong(!)Password' -Query "SELECT * FROM Users;"
After adding data in it, I get this, which is all good:
PS C:\> Invoke-Sqlcmd -ServerInstance '127.0.0.1, 1433' -Database db1 -Username 'SA' -Password 'yourStrong(!)Password' -Query "SELECT * FROM Users;"
id name
-- ----
1 Me
2 You
3 They

Related

Invoke-Sqlcmd returning error: 40 - Could not open a connection to SQL Server

I am trying to use Invoke-Sqlcmd command in PowerShell (version 7):
$Server = 'localhost'
$Database = 'db'
$Query = "PRINT 'This is output'"
$Username = 'root'
$Password = 'pass'
Invoke-SQLCmd -ServerInstance $Server -Database $Database -ConnectionTimeout 2 -QueryTimeout 5 -Query $Query
But getting error:
Invoke-Sqlcmd: A network-related or instance-specific error occurred
while establishing a connection to SQL Server. The server was not
found or was not accessible. Verify that the instance name is correct
and that SQL Server is configured to allow remote connections.
(provider: SQL Network Interfaces, error: 26 - Error Locating
Server/Instance Specified) Invoke-Sqlcmd:
I can connect to DB using Workbench and using mysql command from powershell, but Invoke-Sqlcmd returns this error every time, can anyone point me where the problem is?
As Larnu pointed - I tried to use Invoke-Sqlcmd to connect to MySQL Server which will not work, so I installed MySQL Connector and now able to connect using
$Mysqlhost= "127.0.0.1"
$Mysqluser= "user"
$Mysqlpass= "pass"
$Mysqldatabase= "db"
​
$Connection = [MySql.Data.MySqlClient.MySqlConnection]#{ConnectionString="server=$Mysqlhost;uid=$Mysqluser;pwd=$Mysqlpass;database=$Mysqldatabase"}
$Connection.Open()
$sql = New-Object MySql.Data.MySqlClient.MySqlCommand
$sql.Connection = $Connection
Maybe will be useful for someone.
Thanks to Larnu for pointing to my error.

Load data into SQL Server using Powershell without Credential Prompt

I am trying to load a CSV file into a remote SQL Server instance. This is the command I am running:
Write-SqlTableData -DatabaseName my_db_name -TableName my_table_name -ServerInstance my_server_instance -SchemaName dbo -InputData $data -force
I am trying to use the credential parameter, but it is giving me a prompt. I want to automate this process, so I need to bypass the prompt.
Write-SqlTableData -DatabaseName my_db_name -TableName my_table_name -ServerInstance my_server_instance -SchemaName dbo -Credential $cred -InputData $data -force

Import-pssession SQLPS throws "Arithmetic operation resulted in an overflow" error

I am running PS script from the client machine (Win7) that does not have SQLPS (Ms SQL Server Database Engine) installed.
The script is doing a bunch of SQL queries from two different SQL servers that have the same version (let's call it source and destination).
As the client machine does not have SQLPS installed, I decided to use import-pssession functionality.
Unfortunately, when I import the SQLPS module the third/fourth time, it throws the "Arithmetic operation resulted in an overflow" error.
To simplify what I want, the following is the snippet of my code:
#SQL Query to find out the default folder for sql backup on the SQL SERVER
$tempSQLQuery = "EXECUTE [master].dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory'"
#Source
#Get SQL App Server Credential
$MyCredential = Get-Credential -UserName $($sourceSQLServer + "\" + $sourceSQLServerUsername) -Message "Enter SQL application server Username and Password"
Write-Output "Import SQLPS from source SQL app server"
$Global:P_sourceSQLRemoteSession = New-PSSession -ComputerName $sourceSQLServer -Authentication negotiate -Credential $MyCredential
$sessionID = Import-PSSession -Session $Global:P_sourceSQLRemoteSession -Module SQLPS -DisableNameChecking -AllowClobber
Write-Output "Run query against source SQL Server"
#Run query against source SQL
Invoke-Sqlcmd -ServerInstance $sourceSQLServerInstance -username $sourceSQLServerSA -password $sourceSQLServerSAPassword -query $tempSQLQuery
#Destination
#Get SQL App Server Credential
$MyCredential = Get-Credential -UserName $($destinationSQLServer + "\" + $destinationSQLServerUsername) -Message "Enter SQL application server Username and Password"
Write-Output "Import SQLPS from destination SQL app server"
$Global:P_destinationSQLRemoteSession = New-PSSession -ComputerName $destinationSQLServer -Authentication negotiate -Credential $MyCredential
$sessionID = Import-PSSession -Session $Global:P_destinationSQLRemoteSession -Module SQLPS -DisableNameChecking -AllowClobber
Write-Output "Run query against destination SQL Server"
#Run the same query, against destination SQL server
Invoke-Sqlcmd -ServerInstance $destinationSQLServerInstance -username $destinationSQLServerSA -password $destinationSQLServerSAPassword -query $tempSQLQuery
#Remove session / cleanup
#Remove-PSSession -Session $Global:P_destinationSQLRemoteSession
Now, let's say, I am not importing the SQLPS from the destination SQL server:
#SQL Query to find out the default folder for sql backup on the SQL SERVER
$tempSQLQuery = "EXECUTE [master].dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory'"
#Source
#Get SQL App Server Credential
$MyCredential = Get-Credential -UserName $($sourceSQLServer + "\" + $sourceSQLServerUsername) -Message "Enter SQL application server Username and Password"
Write-Output "Import SQLPS from source SQL app server"
$Global:P_sourceSQLRemoteSession = New-PSSession -ComputerName $sourceSQLServer -Authentication negotiate -Credential $MyCredential
$sessionID = Import-PSSession -Session $Global:P_sourceSQLRemoteSession -Module SQLPS -DisableNameChecking -AllowClobber
Write-Output "Run query against source SQL Server"
#Run query against source SQL
Invoke-Sqlcmd -ServerInstance $sourceSQLServerInstance -username $sourceSQLServerSA -password $sourceSQLServerSAPassword -query $tempSQLQuery
#Remove session / cleanup
#Remove-PSSession -Session $Global:P_sourceSQLRemoteSession
#Destination - with same SQLPS module from source SQL app server
#Get SQL App Server Credential
$MyCredential = Get-Credential -UserName $($destinationSQLServer + "\" + $destinationSQLServerUsername) -Message "Enter SQL application server Username and Password"
Write-Output "Run query against destination SQL Server using source SQL imported module"
#Run the same query, against destination SQL server
Invoke-Sqlcmd -ServerInstance $destinationSQLServerInstance -username $destinationSQLServerSA -password $destinationSQLServerSAPassword -query $tempSQLQuery**
The following error is resulted:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
What do you think could cause this issue?
Can you think of an alternative method to achieve what I want? should I just have the client machine that will run PS1 script to install SQL module/add-on?
Thanks heaps!

Invoke-SQLCMD fails on SQL Cluster

I am trying to use the invoke-sqlcmd on a SQL Server Cluster but it fails to execute and produces the following error:
invoke-sqlcmd : A network-related or instance-specific error occurred
while establishing a connection to SQL Server. The server was not
found or was not accessible. Verify that the instance name is correct
and that SQL Server is configured to allow remote connections.
(provider: Named Pipes Provider, error: 40 - Could not open a
connection to SQL Server) At
C:\rs-pkgs\SitecoreDeployScripts\SitecoreDatabasesDeploy.ps1:128
char:1
+ invoke-sqlcmd -InputFile $inputFilePath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Invoke-Sqlcmd], SqlException
+ FullyQualifiedErrorId : SqlExectionError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
I am able to execute my script successfully on a development SQL Box that is not clustered. Here is an example of the SQL invocation:
$scriptPath = "C:\"
$scriptName = "MyScript.sql"
$inputFilePath = "{0}\{1}" -f $scriptPath,$scriptName
invoke-sqlcmd -InputFile $inputFilePath
So the question is this a Cluster issue or a security issue with remote connections not being allowed? How do I get the SQL Scripts to execute from PowerShell (the execute correctly if I open them in SSMS and press execute).
In then end the script just needed the Server Instance name switch of -ServerInstance as follows:
$scriptPath = "C:\"
$scriptName = "MyScript.sql"
$inputFilePath = "{0}\{1}" -f $scriptPath,$scriptName
invoke-sqlcmd -InputFile $inputFilePath -ServerInstance 'MyClusterName"
I located the name by running the following query:
select ##servername
It works on a single box without the -ServerInstance switch since it is localized/single

Connecting to remote SQL Server instance using SQL auth via SqlPowershell?

I'm trying to use SqlPowershell/SqlPS (Import-Module sqlps) to connect to a server on my local network. I followed the instructions here to create a function that predefines a server/database and the login and prompts each time for the password:
function sqldrive
{
param( [string]$name, [string]$login = "<myLogin>", [string]$root = "SQLSERVER:\SQL\<serverName>\<databaseName>" )
$pwd = read-host -AsSecureString -Prompt "Password"
$cred = new-object System.Management.Automation.PSCredential -argumentlist $login,$pwd
New-PSDrive $name -PSProvider SqlServer -Root $root -Credential $cred -Scope 1
}
However, after running sqldrive <someName> and entering my password, it fails to connect, giving two messages:
WARNING: Could not obtain SQL Server Service information. An attempt to connect to WMI on '<serverName>' failed with
the following error: The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
and
New-PSDrive : SQL Server PowerShell provider error: Path SQLSERVER:\SQL\<serverName>\<databaseName> does not exist. Please
specify a valid path.
At line:6 char:5
+ New-PSDrive $name -PSProvider SqlServer -Root $root -Credential $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (SQLSERVER:\SQL\<serverName>\<databaseName>:String) [New-PSDrive], GenericProviderException
+ FullyQualifiedErrorId : PathDoesNotExist,Microsoft.PowerShell.Commands.NewPSDriveCommand
Can anyone spot where I'm going wrong? I can work with the same server just fine using those credentials via SSMS.

Resources