How to query SQL Server using PowerShell? - sql-server

I found some code online but so far I can't get it to connect to my SQL Server database. I have followed this website to the letter: https://blogs.msdn.microsoft.com/walzenbach/2010/04/14/how-to-enable-remote-connections-in-sql-server-2008/
I have allowed remote connections, added port 1433 to my firewall etc. I then run this code from PowerShell ISE:
$dataSource = “\\SCCM12-01\MSSQLSERVER”
$user = “MyID\OurDomain.org”
$pwd = “MyPassword”
$database = “CM1”
$connectionString = “Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;”
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
when I run this I get the following error.
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: SQL Network Interfaces, error: 25 - Connection
string is not valid)"

If you have simple query to do I recommend Select-SQLView powershell module. It allows to quickly select rows from table or view. It stores your database and server name so you do not have to provide this values every time.
As usual You can push results to table or to GridView.
If more complex queries are needed use SQLCommands module.

Not sure why you are getting this error. You can refer to this link https://github.com/Tervis-Tumbler/InvokeSQL
You can try this one-
function Invoke-SQL {
param(
[string] $dataSource = ".\SQLEXPRESS",
[string] $database = "MasterData",
[string] $sqlCommand = $(throw "Please specify a query.")
)
$connectionString = "Data Source=$dataSource; " +
"Integrated Security=SSPI; " +
"Initial Catalog=$database"
$connection = new-object system.data.SqlClient.SQLConnection($connectionString)
$command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
$connection.Open()
$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataSet) | Out-Null
$connection.Close()
$dataSet.Tables
}

The error message actually explains what's wrong:
"SQL Network Interfaces, error: 25 - Connection string is not valid".
There is something amiss on the connection string. What exactly is hard to say as you have masked most of the details. Maybe the smart quotes wreck things? Maybe you got a quote character in the password? Anyway, it looks like you have invalid parameter for the user id:
$connectionString = “Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;”
Try User Id instead of uid like so,
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;

You properly just need to change 'Integrated Security' to 'true' when not using a db login
**Integrated Security=True**

Related

Querying Linked Server in Powershell

Wondering if yall can help me resolving an error I'm receiving when using Invoke-Sqlcmd to query a linked server in powershell. Thank you for any help you might be able to provide!
Here's my code
$SQLServer = "SERVER1"
$database = "Database1"
$query = "
SELECT
a.id,
a.location,
a.name,
b.office
FROM [SERVER1].[Database1].[dbo].[Table1] a
LEFT JOIN [SERVER1].[Database1].[dbo].[Table2] b ON b.id = a.id
"
Invoke-Sqlcmd -ServerInstance $SQLServer -Database $database -Query $query
Here's the error I receive:
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)
In my experience working with powershell and SQL I've been unable to get Invoke-SQL command to work properly. I have however used this method with much success.
You can change the integrated security to true and it will use the currently logged in Windows account to authenticate with the SQL server instead of providing the credentials in the script.
#creates connection, enter the SQL server host name, the user and password.
$connectionString = “Server=#SQLServer;uid=$User2; pwd=$pwdencrypt2;Integrated Security=False;”
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
#This will be your query bulk insert as an example
[string]$queryCL1 = "
BULK INSERT [Databasename].[dbo].[tablename]
FROM 'filepath'
WITH(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n',
FIRSTROW = 2
)"
#this uses the set variables to build and execute the command with execute reader
$command = $connection.CreateCommand()
$command.CommandText = $queryCL1
$command.CommandTimeout=0
$resultCL1 = $command.ExecuteReader()

How to use ApplicationIntent=ReadOnly inside my powershell code in SQL command

I need to use ApplicationIntent=ReadOnly with my SQL command in powershell which is connecting to a replica database. Can anyone help ?
Since replicas servers could not be accessed directly. So I need to use this command. I know how to manually do it but need help on code.
$SQLQuery = "SELECT x.SCode, x.DatabaseName FROM dbo.Logins x ORDER BY x.SCode"
$auth = #{Username = $SQLUserName; Password = $SQLAdminPassword}
try
{
$allTenants = Invoke-Sqlcmd -Query $SQLQuery -ServerInstance $SQLServerName -Database 'SShared'-QueryTimeout -0 #Auth -ErrorAction Stop
Write-Log -LogFileName $logfile -LogEntry ("Found {0} tenants" -f $allTenants.Count)
}
I am geeting the below error using this -
Exception Message 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)
There's a few ways that you can do this.
Easy way
dbatools
There is a PowerShell module for interacting with SQL Server created by the SQL Server community called dbatools.
In the module, there is a function called Invoke-DbaQuery which is essentially a wrapper for Invoke-Sqlcmd.
This function has a parameter, -ReadOnly, that you can use that was created exactly for this scenario.
# Changing your $auth to a PSCredential object.
$cred = [System.Management.Automation.PSCredential]::New(
$SqlUserName,
(ConvertTo-SecureString -String $SqlAdminPassword -AsPlainText -Force))
# Splatting the parameters for read-ability.
$QueryParams = #{
Query = $SQLQuery
SqlInstance = $SQLServerName
Database = 'SShared'
QueryTimeout = 0
SqlCredential = $cred
ReadOnly = $true # <-- Specifying read-only intent.
ErrorAction = 'Stop'
}
$allTenants = Invoke-DbaQuery #QueryParams
Other way
Invoke-Sqlcmd
If you can't, won't, don't want to use dbatools, you can still use Invoke-Sqlcmd. The latest release at the time of writing, has the option to specify the parameter -ConnectionString.
You can state that it's read-only there.
# Splatting again for read-ability.
$SqlcmdParams = #{
Query = $SQLQuery
QueryTimeout = 0
ConnectionString = "Data Source=$SQLServerName;Initial Catalog=SShared;User ID=$SqlUserName;Password=$SqlAdminPassword;Integrated Security=false;ApplicationIntent=ReadOnly" # <-- Specifying read-only intent.
ErrorAction = 'Stop'
}
Invoke-Sqlcmd #SqlcmdParams

Remote connection string to database fails for username, but can access via Studio Manager

Whilst my Windows AD account has datareader access to a SQL 2012 database (can access via SQL Studio Manager, perform queries etc), my login seems to fail when I try to perform the same query via a SQL connection through a Powershell script.
So I log into the Computer with my AD Account, same as specified in UID in the connection string, and Powershell is launched under the same account.
This is the SQL Query invoked within Powershell:
$ADComputer='Server1'
$sqlParameters = New-Object System.Data.SqlClient.SqlParameter('#ServerName', $ADComputer)
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=<servername>;Database=<databasename>;Uid=<domain\user>;Pwd=<password>"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText =
"SELECT TOP 1 MAX(CIA.EnforcementDeadline) AS EnforcementDeadline
FROM v_collection, v_FullCollectionMembership FCM
INNER JOIN v_Collection COL
ON FCM.CollectionID = COL.CollectionID
INNER JOIN v_CIAssignment CIA
WHERE FCM.CollectionID NOT IN ('SMS00001','SMSDM003')
AND FCM.Name='$ADComputer'"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlConnection.Close()
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0]
$LastUpdateDate = $DataSet.Tables[0]
$LastUpdate = $LastUpdateDate | Select Column1 -Expandproperty Column1
Exception calling "Fill" with "1" argument(s): "Login failed for user '<domain\user>'."
It's as if the connection string doesn't notice what's specified.
However, if I remove the UID and PWD and add "Integrated Security" it then works:
$SqlConnection.ConnectionString = "Server=<servername>;Database=<databasename>;Integrated Security=SSPI"
I have also discovered that the line
$SqlAdapter.Fill($DataSet)
Is where the error occurs. Admittedly, I don't consider myself a guru in PS as I am learning, but it sounds as if this could be writing something somewhere that may cause write permission issues?
Hope someone can help or at least explain why it's failing.
thanks
You can't login to SQL Server using a domain account specified in the connection string.
You can either specify user name and password in the connection string using a SQL authentication user (if you enabled Mixed Mode Authentication on the server) or specify "Integrated Security=True" to use current process credentials.
https://msdn.microsoft.com/en-us/library/bb669066(v=vs.110).aspx

$con.Open() doesn't work in foreach, but works when directly used

I have a code snippet that is used to connect to a SQL Server Instance, and query, this works fine.
$instance="Instance"
$DB = "master"
$sqlConnection = ConnectionString $Instance $DB
$sqlConnection = New-Object System.Data.SqlClient.SQLConnection($sqlConnection)
$sqlConnection.Open()
However, the same code snippet, if put into a foreach loop, where it has to iterate through a set of servers, it doesn't work.
foreach ($instance in $Instances) {
$instance
$DB = "master"
$sqlConnection = ConnectionString $Instance $DB
$sqlConnection = New-Object System.Data.SqlClient.SQLConnection($sqlConnection)
$sqlConnection.Open()
}
Error:
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)"
Ansgar is correct. You shouldn't reuse variable names.
An easier way to implement this is using the Invoke-Query module, which collapses most of your code to a single line.
$sql = "Update myTable set myColumn = 1;"
$db= "master"
$instances = ("instance1","instance2")
foreach ($instance in $instances)
## This command uses windows auth.
## You can pass in a Credential object to use SqlServer auth.
$rowcount = $sql | Invoke-SqlServerQuery -Server $instance -Database $db -CUD
Write-Host "Updated $rowcount rows on server $instance."
}
Disclaimer: I'm the author of the module.

Connect to SQL Server Database from PowerShell

I have looked around online for a while now and found many similar problems but for some reason I can't seem to get this working.
I am just trying to connect to a SQL server database and output the query results to a file - See PowerShell script below. What I am uncertain about is how to integrate the User ID and Password into the connection string.
$SQLServer = "aaaa.database.windows.net"
$SQLDBName = "Database"
$uid ="john"
$pwd = "pwd123"
$SqlQuery = "SELECT * from table;"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True; User ID = $uid; Password = $pwd;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0] | out-file "C:\Scripts\xxxx.csv"
The following error message is received:
Exception calling "Fill" with "1" argument(s): "Windows logins are not supported in this version of SQL Server."
Integrated Security and User ID \ Password authentication are mutually exclusive. To connect to SQL Server as the user running the code, remove User ID and Password from your connection string:
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"
To connect with specific credentials, remove Integrated Security:
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; User ID = $uid; Password = $pwd;"
Change Integrated security to false in the connection string.
You can check/verify this by opening up the SQL management studio with the username/password you have and see if you can connect/open the database from there. NOTE! Could be a firewall issue as well.
# database Intraction
$SQLServer = "YourServerName" #use Server\Instance for named SQL instances!
$SQLDBName = "YourDBName"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName;
User ID= YourUserID; Password= YourPassword"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = 'StoredProcName'
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
#End :database Intraction
clear
The answer are as below for Window authentication
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$SQLServer;Database=$SQLDBName;Integrated Security=True;"
Assuming you can use integrated security, you can remove the user id and pass:
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"
To connect to SQL Server as an active directory user just start the PowerShell as an active directory user and connect to SQL Server with TrustedSecurity=true
I did remove integrated security ... my goal is to log onto a sql server using a connection string WITH active directory username / password. When I do that it always fails. Does not matter the format ... sam company\user ... upn whatever#company.com ... basic username.
I think that may work only if the specific user in question is explicitly set up to log in with a password on the SQL server database i.e. without inheriting credentials from integrated Windows / single-sign-on

Resources