I'm having an issue connecting to a SQL Server using SMO when using a ServerConnection. For the last few months this has been working, but now failing. Here is a snippet of the script:
$svrname = "Server"
#Establish Server connection
Write-ColorOutput "Establishing SQL Server Connection to $svrName" "White"
$mysvrConn = new-object Microsoft.SqlServer.Management.Common.ServerConnection
$mysvrConn.ServerInstance=$svrName
$mysvrConn.LoginSecure = $false
$mysvrConn.Login = "Admin"
$mysvrConn.Password = "Password"
$svr = new-object 'Microsoft.SqlServer.Management.SMO.Server' $mysvrConn
However, the following works.
$svrname = "Server"
$svr = new-object ('Microsoft.SQLServer.Management.SMO.Server') $svrname
And the assemblies:
Write-ColorOutput "Loading assemblies" "White"
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SQLServer.Smo") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null
You almost certainly have permission issues with your SQL login. You are either using the wrong password, or the login does not have the proper creds.
Embarrassingly, when I had this issue, it turned out to be that I had entered the login password incorrectly.
I had expected a specific error stating the login failed. Instead it was the more generic: Failed to connect to server localhost., which threw me off.
Like you, I ran a test with the $LoginSecure = $True which worked, telling me that the connection to the server was fine. Only then did I spot my typo and was on my way to SMO bliss.
Related
I am looking something to setup alert notification when SQL agent is down, sometimes when windows patch apply or server get rebooted SQL Agent is not restarting even though we have set up SQL Agent properties Auto Restart SQL Server if it stops unexpectedly
Auto Restart SQL Server Agent if it stops unexpectedly.
I have also tried to setup services on Component service on server to at Recovery tab, First Failure Restart the service and also restarted service rebooted but didn't work.
Is it any way I can get the alert so I can restart service manually when it's Agent is down it it will trigger to restart the job when Agent it's down.
$AgentStatus = (Get-Service -ComputerName <CompName> -Name <SqlServerAgentName> | Where-Object {$_.Status -eq "Stopped"} | Measure-Object).Count
If($AgentStatus -eq 1){
Start-Service -Name SqlServerAgentName
$SMPTPort = <Specify port number>
$From = "email1#domain.com"
$To = "email2#domain.com"
$Subject = "The SQL Server Agent Service in $env:ComputerName has been restarted."
$Body = "The SQL Server Agent Service <SqlServerAgentName> was in a Stopped state and has been restarted."
$SMTPServer = "SMTP SERVER"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, $SMPTPort)
$SMTPClient.EnableSsl = $false
$SMTPClient.Send($From, $To, $Subject, $Body)}
You can try creating a batch file below which checks for service status. This sends an SMTP mail (using powershell) along with restarting service again.
for /F "tokens=3 delims=: " %%H in ('sc query "MyServiceName" ^| findstr " STATE"') do (
if /I "%%H" NEQ "RUNNING" (
powershell -ExecutionPolicy ByPass -Command Send-MailMessage -SmtpServer SMTPSERVER -To someone#domain.com -From noreply#domain.com -Subject Testing -Body Service_Not_Running
net start "MyServiceName"
)
)
Once you have the script ready, create a task scheduler to call the batch file. Run the scheduler every 1 hr or so.
I tried to query my syslogins with this script in powershell. It gives me this error:
"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.
The error shown:
provider: Named Pipes Provider, error: 40 - Could not open a
connection to SQL Server
Remote Access is enabled on the Database I try to connect to.
This is the code im working with:
$conn = New-Object System.Data.SqlClient.SqlConnection
$cmd = New-Object System.Data.SqlClient.SqlCommand
$conn.ConnectionString = "server=servername.hsr.ch;database=mydb;Integrated Security=true;"
$conn.open()
$cmd.Connection = $conn
$cmd.CommandText = "SELECT * FROM syslogins"
$out = $cmd.ExecuteNonQuery()
$conn.close()
print $out
I am trying to put bWAPP on my spare webserver for me and my friends to use.
It's locked by a password and stuff, so only people who know it can use it.
Here's the configuration I have right now.
$db_server = "atroxis.net";
$db_username = "ethereal_atrox";
$db_password = "(redacted)";
$db_name = "ethereal_bwapp";
The password is right, I just redacted it.
I keep getting this SQL error.
Connection failed: Access denied for user 'ethereal_atrox'#'51.38.85.24' (using password: YES)
Anyone have any ideas?
Try to put:
$db_server = "localhost";
and reload apache.
If it doesn't work, verify the file connect.php and change myql_ for mysqli_
I use the following command to connect to remote database:
$SQLServer = "Servername"
$SQLDBName = "DBname"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; User ID= username; Password= password"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "INSERT INTO dbo.Tablename(ReceivedTime, Subject)VALUES($time, $subject)"
$SqlCmd.Connection = $SqlConnection
But have the following err message:
Exception calling "Open" with "0" argument(s): "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 line:10 char:1
$conn.Open()
~~~~~~~~~~~~
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : SqlException
I need to connect to the remote server and online solutions mainly focus on the local servers, so they are not suitable for me. (Company server/database and network, maybe different from local server?)
Hope you can help me improve the code or provide with some solutions. Thanks all.
This is partially my code and partially from others help here on stack overflow.
$excelFile = "C:\ExcelTest\Test.csv"
$functionDirectory = "C:\foldername"
$csv = Import-csv $excelFile -Header FileName
Import-Module sqlps
foreach ($line in $csv)
{
if(test-path -path ($functionDirectory + "\" + $line.FileName))
{
invoke-sqlcmd -inputfile "C:\foldername\filename.sql" -serverinstance "servername\instancename" -database "databasename"
}
}
I had to remove the specific serverinstance / servername for privacy but I've checked both of those several times and I don't think that is where the issue is. I keep getting the error
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.
I have double checked server / instance name which I got from the server by running
select ##servername + '\' + ##SERVICENAME
nd the database name obviously was easy to get. I have double checked that the server is set up for remote connection (even though this is a database that is local on my laptop and not a remote server currently).
I'm kinda at a loss for what else to check for.
I had read you should look at firewall settings but I don't think those should make a difference when its a local server on my machine.
I'm still somewhat new with SQL and powershell so I apologize for any blatant syntax or formatting errors (please point out so I can correct them). Any help would be appreciated.
Turns out I needed to remove the instance name and just use the server name.