Querying Linked Server in Powershell - sql-server

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()

Related

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

Connecting to SQL Server with SQL Server account and encrypted password and executing invoke-sqlcmd

Would really appreciate some help. I have a PowerShell script which I use to update columns in a SQL Server table. When this uses a domain account it works fine.
However, I want to run during user login, and use a SQL Server account, not Windows account, but I can't figure out why it isn't working.
When the key/txt file uses the domain account, no problems. But when replace with SQL Server account details, no go.
$SQLUser = "Username"
$SQLPasswordFile = "\\pathto\UserPW.txt"
$SQLKeyFile = "\\pathto\UserPW.key"
$SQLkey = Get-Content $SQLKeyFile
$SQLMyCredential = New-Object -TypeName System.Management.Automation.PSCredential `
-ArgumentList $SQLUser, (Get-Content $SQLPasswordFile | ConvertTo-SecureString -Key $SQLkey)
$SQLCredentials = Get-Credential -Credential $SQLMyCredential
$SQLSession = New-PSSession -ComputerName "uhpkpdb01" -Credential $SQLCredentials
Invoke-Command -Session $SQLSession -ScriptBlock {
$exist = Invoke-Sqlcmd "select count(1) from [table] where USER_NAME = '$($args[0])'" -ServerInstance "SERVERNAME"
if ($exist.column1 -eq "1") {
Invoke-Sqlcmd "UPDATE [table] SET PASSWORD = '$($args[1])' WHERE USER_NAME = '$($args[0])'"
Write-Host "Account Updated" }
else {
Write-Host "User Does Not Exists"}} -ArgumentList $env:USERNAME, "PASSWORD"
Remove-PSSession $SQLSession
I am getting
New-PSSesion : Connecting to remote server failed with : The user name or password is incorrect.
I can connect using the SQL Server account to SSMS and open and update table.
I must be passing the user name incorrectly, but can't figure out how to do it properly.
Any assistance would be greatly appreciated.
You cannot pass a PSCredential object that contains your SQL Login to Invoke-Command. The only thing that command understands is Windows Credentials.
You can pass and call the Invoke-SqlCmd command directly from your own machine if you have the module installed.
If you need to use the SQL Login on a remote session you will have to pass that credential object into the remote session so it can be utilized within your script block.

How to query SQL Server using PowerShell?

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**

$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.

How to import data from .csv in SQL Server using PowerShell?

I'm using PowerShell and have to import data from a .csv file into a already created table on a SQL Server Database. So I don't need the header line from the csv, just write the data.
Here is what I have done so far:
#Setup for SQL Server connection
#SQL Server Name
$SQLServer = "APPLIK02\SQLEXPRESS"
#Database Name
$SQLDBName = "code-test"
#Create the SQL Connection Object
$SQLConn = New-Object System.Data.SQLClient.SQLConnection
#Create the SQL Command Object, to work with the Database
$SQLCmd = New-Object System.Data.SQLClient.SQLCommand
#Set the connection string one the SQL Connection Object
$SQLConn.ConnectionString = "Server=$SQLServer;Database=$SQLDBName; Integrated Security=SSPI"
#Open the connection
$SQLConn.Open()
#Handle the query with SQLCommand Object
$SQLCmd.CommandText = $query
#Provide the open connection to the Command Object as a property
$SQLCmd.Connection = $SQLConn
#Execute
$SQLReturn=$SQLCmd.ExecuteReader()
Import-module sqlps
$tablename = "dbo."+$name
Import-CSV .\$csvFile | ForEach-Object Invoke-Sqlcmd
-Database $SQLDBName -ServerInstance $SQLServer
#-Query "insert into $tablename VALUES ('$_.Column1','$_.Column2')"
#Close
$SQLReturn.Close()
$SQLConn.Close()
I wrote a blog post about using SQL with PowerShell, so you can read more about it here.
We can do this easily if you have the SQL-PS module available. Simply provide values for your database name, server name, and table, then run the following:
$database = 'foxdeploy'
$server = '.'
$table = 'dbo.powershell_test'
Import-CSV .\yourcsv.csv | ForEach-Object {Invoke-Sqlcmd `
-Database $database -ServerInstance $server `
-Query "insert into $table VALUES ('$($_.Column1)','$($_.Column2)')"
}
To be clear, replace Column1, Column2 with the names of the columns in your CSV.
Be sure that your CSV has the values in the same format as your SQL DB though, or you can run into errors.
When this is run, you will not see any output to the console. I would recommend querying afterwards to be certain that your values are accepted.

Resources