Add SQL Server Instances to Central Management Server Groups with Powershell - sql

I am trying to create a script to automatically iterate through a text file of all our SQL Server instances and add each on if it doesn't already exist to the CMS. I want to try doing this through SMO instead of hardcoding sql strings in. Below is what I have so far but it doesn't seem to be working. Any help would be appreciated. Thanks.
Eventually I will add more If statements in to distribute the instances to certain groups but for now I'm just trying to get it to populate everything.
$CMSInstance = "cmsinstancename"
$ServersPath = "C:\Scripts\InPutFiles\servers.txt"
#Load SMO assemplies
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Management.RegisteredServers') | out-null
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Management.Common') | out-null
$connectionString = "Data Source=$CMSINstance;Initial Catalog=master;Integrated Security=SSPI;"
$sqlConnection = new-object System.Data.SqlClient.SqlConnection($connectionString)
$conn = new-object Microsoft.SqlServer.Management.Common.ServerConnection($sqlConnection)
$CMSStore = new-object Microsoft.SqlServer.Management.RegisteredServers.RegisteredServersStore($conn)
$CMSDBStore = $CMSStore.ServerGroups["DatabaseEngineServerGroup"]
$Servers = Get-Content $ServersPath;
foreach($Server in $Servers)
{
#Put this in loop to deal with duplicates in list itself
$AlreadyRegisteredServers = #()
$CMSDBStore.GetDescendantRegisteredServers()
$RegServerName = $Server.Name
$RegServerInstance = $Server.Instance
if($AlreadyRegisteredServers -notcontains $RegServerName)
{
Write-Host "Adding Server $RegServerName"
$NewServer = New-Object Microsoft.SqlServer.Management.RegisteredServers.RegisteredServer($CMSDBStore, "$RegServerName")
$NewServer.SecureConnectionString = "server=$RegServerInstance;integrated security=true"
$NewServer.ConnectionString = "server=$RegServerInstance;integrated security=true"
$NewServer.ServerName = "$RegServerInstance"
$NewServer.Create()
}
else
{
Write-Host "Server $RegServerName already exists - cannot add."
}
}

I cut your script down to just the basics and it works for me. I did have to change the connection command to work in my environment but other than that and registering a default instance of SQL Server there were no errors. Once I did a refresh of the CMS server the newly registered server was visible and accessible.
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Management.RegisteredServers') | Out-Null
$CMSInstance = 'CMS_ServerName'
$connectionString = "Data Source=$CMSInstance;Initial Catalog=master;Integrated Security=SSPI;"
$sqlConnection = new-object System.Data.SqlClient.SqlConnection($connectionString)
$conn = New-Object System.Data.SqlClient.SqlConnection("Server=$CMSInstance;Database=master;Integrated Security=True")
$CMSStore = new-object Microsoft.SqlServer.Management.RegisteredServers.RegisteredServersStore($conn)
$CMSDBStore = $CMSStore.ServerGroups["DatabaseEngineServerGroup"]
$RegServerName = 'ServerToRegister'
$RegServerInstance = $RegServerName
$NewServer = New-Object Microsoft.SqlServer.Management.RegisteredServers.RegisteredServer($CMSDBStore, "$RegServerName")
$NewServer.SecureConnectionString = "server=$RegServerInstance;integrated security=true"
$NewServer.ConnectionString = "server=$RegServerInstance;integrated security=true"
$NewServer.ServerName = "$RegServerInstance"
$NewServer.Create()

Related

How to connect to and populate SQL database using Powershell

I want to write an application that talks to a database. The databases are created through phpmyadmin interface. I can talk to these fine through php. What I would like is to populate these databases using a powershell script.
How do I connect to the database ? How do I populate a database ? I can't seem to find any good starting points.
Here is a great place to start:
https://dbatools.io/
https://dbareports.io/
or you can look here as well:
https://www.powershellgallery.com/
Here's a function to handle this type of task
function Invoke-SQL
{
param (
[string]$server,
[string]$database,
[string]$Query
)
$connectionString = "Data Source=$server; " +
"Integrated Security=SSPI; " +
"Initial Catalog=$database"
$connection = new-object
system.data.SqlClient.SQLConnection($connectionString)
$command = new-object system.data.sqlclient.sqlcommand($Query, $connection)
$connection.Open()
$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
# Use these to populate info #
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataSet) | Out-Null
$connection.Close()
# displays info #
$dataSet.Tables
}
Here's an example of updating the SQL Database
Invoke-SQL -server 'server' -database 'database' -Query "UPDATE [database].[dbo].[Local] SET Field1 = '$InfoForField1', Field2 = '$InfoForField2'"
You can do whatever you need using this method, as long as you know your SQL queries and how to populate the varaibles with the correct information that you need.

How can I connect to SQL through PowerShell using Windows authentication other than my local one?

Here's my current code:
[string] $Server= "server"
[string] $Database = "database"
[string] $UserSqlQuery= $("SELECT * FROM [dbo].[User]")
[string] $UserID = "userid"
[string] $Pass = "pass"
$resultsDataTable = New-Object System.Data.DataTable
$resultsDataTable = ExecuteSqlQuery $Server $Database $UserSqlQuery $UserId $Pass
# executes a query and populates the $datatable with the data
function ExecuteSqlQuery ($Server, $Database, $SQLQuery, $UserID, $Pass) {
$Datatable = New-Object System.Data.DataTable
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;User ID = '$UserID';Password='$Pass';"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = $SQLQuery
$Reader = $Command.ExecuteReader()
$Datatable.Load($Reader)
$Connection.Close()
return $Datatable
}
#validate we got data
Write-Host ("The table contains: " + $resultsDataTable.Rows.Count + " rows")
So I realize I can replace UserID and Password with Integrated Security=true in order to use Windows authentication. The problem is I'm trying to use a Windows authentication other than my current one to get on SQL. Is there any way to do this? Thanks.
If the SQL connection string needs to specify Integrated Security then user impersonation will be needed. If you hold down the shift key and right click the powershell icon you can run the powershell process as another user by selecting "Run As" and entering the correct Windows credentials.
If the script must start running under one Windows user, but then impersonate a different Windows user for the SQL connection, then some additional scripting will be needed to setup that impersonation. Here's a link that may be useful in working that out - http://poshcode.org/1867

Powershell - SQL Server - connectionstring in loop for multiple Instances

Thisis part of a bigger script which finds DatabaseFiles on a SQL Server machine (multiple instances).
Following should just return all files for 3 instances.
The server is called V3000801 and there is one default instance + 2 named instances on there. It's ok with me if either default or named doesn't work I'll work around this alone (most likely create a flag and do default with another connection string).
$SqlCmd.ExecuteNonQuery() just returns -1 which does not make any sense for me.
Thanks for the help
for($i=0;$i -lt $instances.Length;$i++){
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection;
$Server= "V3000801\"+$instances[$i];
$SqlConnection.ConnectionString = "Server = $server ; Database = master; Integrated Security = sspi;trusted_connection=true";
$sqlQuery="SELECT physical_name FROM sys.master_files;";
Write-Host $SqlConnection.ConnectionString;
$SqlConnection.Open();
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand;
$SqlCmd.CommandText = $sqlQuery;
$SqlCmd.Connection = $SqlConnection;
$SqlCmd.ExecuteNonQuery();
$SqlConnection.Close();
}
the link posted by #jody contains some good information
try:
$dr= $SqlCmd.ExecuteReader()
while ($dr.Read())
{
$dr.GetValue(0)
}
$sqlconnection.Close()
Use the ExecuteReader function for selects. ExecuteNonQuery is used for operations that do not return any results such as inserts, updates and deletes.
Here is an example in .NET but it should be similar in PowerShell.
EDIT:
This code should work. I tried it out on my own environment (with a different server name).
for($i=0;$i -lt $instances.Length;$i++){
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection;
$Server= "V3000801\"+$instances[$i];
$SqlConnection.ConnectionString = "Server = $server ; Database = master; Integrated Security = sspi;trusted_connection=true";
$sqlQuery="SELECT physical_name FROM sys.master_files;";
Write-Host $SqlConnection.ConnectionString;
$SqlConnection.Open();
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand;
$SqlCmd.CommandText = $sqlQuery;
$SqlCmd.Connection = $SqlConnection;
$reader = $SqlCmd.ExecuteReader();
while ($reader.Read())
{
"pfad=" $reader["physical_name"];
};
$SqlConnection.Close();
}

SQL DB export using powershell

I am attempting to export BLOB data for images stored in a remote SQL server and save them to an export folder in .jpg on the local machine. Any assistance in troubleshooting the first error or helping me modify the working connection to pull the blob data and convert it to .jpgs on the local machine would be much appreciated.
I found the following code
$Server = "?????"
$Database = "??????"
$Dest = "c:\Export\"
$bufferSize = 8192
$sqlCommand = " SELECT ID?????1
FROM dbo.W?????e; "
$authentication = "Integrated Security=SSPI;"
$connectionString = "Provider=sqloledb; " +
"Data Source=$dataSource; " +
"Initial Catalog=$database; " +
"$authentication; "
$connection = New-Object System.Data.OleDb.OleDbConnection $connectionString
$command = New-Object System.Data.OleDb.OleDbCommand $sqlCommand,$connection
$connection.Open()
$reader = $command.ExecuteReader()
$out = [array]::CreateInstance('Byte', $bufferSize)
While ($reader.Read())
{
$fileStream = New-Object System.IO.FileStream ($Dest + $reader.GetString(0)), Create, Write
$binaryWriter = New-Object System.IO.BinaryWriter $fileStream
$start = 0
$received = $reader.GetBytes(1, $start, $out, 0, $bufferSize - 1)
While ($received -gt 0)
{
$binaryWriter.Write($out, 0, $received)
$binaryWriter.Flush()
$start += $received
$received = $reader.GetBytes(1, $start, $out, 0, $bufferSize - 1)
}
$binaryWriter.Close()
$fileStream.Close()
}
$fileStream.Dispose()
$reader.Close()
$command.Dispose()
$connection.Close()
I am getting errors when running the code.
I can connect to the database using this code, but I dont understand the streamprocess enough to mesh the code to do what I want
$Server = "?????"; # SQL Server Instance.
$Database = "?????";
$Dest = "c:\Export\"; # Path to export to.
$bufferSize = 8192; # Stream buffer size in bytes.
$connString = "data source=?????,1433;Initial catalog=?????;Integrated Security=TRUE;"
$QueryText = "SELECT ID?????1
FROM dbo.W??????e;"
$SqlConnection = new-object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $connString
$SqlCommand = $SqlConnection.CreateCommand()
$SqlCommand.CommandText = $QueryText
$DataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $SqlCommand
$dataset = new-object System.Data.Dataset
$DataAdapter.Fill($dataset)
$dataset.Tables[0]
Write-Output ("Finished");
This is what I am trying to accomplish, but I am getting errors casting the bytes to string
HERE
I bet your command timeout is too short. By default, it is 30 seconds. Blobs are usually very large, and I wouldn't be surprised if it is taking longer than 30 seconds to read them all from the database. Try setting the timeout to something really, really large:
$command.CommandTimeout = [Int32]::MaxValue
I got the same error.
Reading the original code a little closer the SQL Server name is for an instance. If you are executing this on the local server you can use "." as the server name.
$Server = ".";

Powershell Function SQL Stored Procedure with Parameters

The error received is "The SqlParameterCollection only accepts non-null SqlParameter type objects, not SqlCommand objects." & "Procedure or function 'usp__SingleUpdateServerBackupPath' expects parameter '#decServerName', which
was not supplied."
PowerShell code:
Set-StrictMode -Version 1.0
function update-serverbackuppath {
param(
[Parameter(Mandatory=$True,ValueFromPipeLine=$True)][object[]]$inputobject
)
BEGIN {
$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection
$connection.ConnectionString = "server=servername;database=database;trusted_connection=yes"
$connection.Open()
}
PROCESS {
$UpdateBackupPath = New-Object -TypeName System.Data.SqlClient.SqlCommand
$UpdateBackupPath.Connection = $connection
$UpdateBackupPath.CommandText = "usp__SingleUpdateServerBackupPath"
$UpdateBackupPath.Commandtype = [System.Data.Commandtype]::StoredProcedure
$ParamUpdateBackupPath = New-Object -TypeName System.Data.SqlClient.SqlParameter
$ParamUpdateBackupPath.ParameterName = "#decBackupPath"
$ParamUpdateBackupPath.SqlDbType = [System.Data.SqlDbType]::VarChar
$ParamUpdateBackupPath.Direction = [System.Data.ParameterDirection]::Input
$ParamUpdateBackupPath.Value = $inputobject.paths
$ParamUpdateBackupPathServerName = New-Object -TypeName System.Data.SqlClient.SqlCommand
$ParamUpdateBackupPathServerName.ParameterName = "#decServerName"
$ParamUpdateBackupPathServerName.SqlDbType = [System.Data.SqlDbType]::VarChar
$ParamUpdateBackupPathServerName.Direction = [System.Data.ParameterDirection]::Input
$ParamUpdateBackupPathServerName.Value = $inputobject.names
$UpdateBackupPath.Parameters.Add($ParamUpdateBackupPath)
$UpdateBackupPath.Parameters.Add($ParamUpdateBackupPathServerName)
$reader = New-Object -TypeName System.Data.SqlClient.SqlDataReader = $UpdateBackupPath.ExecuteReader()
}
END {
$connection.Close()
}
}
SQL Procedure:
Create Procedure usp__SingleUpdateServerBackupPath
(
#decBackupPath AS varchar(50),
#decServerName AS varchar(50)
)
AS
UPDATE BCKP
SET PTH = #decBackupPath
FROM BCKP
INNER JOIN SRVR
ON SRVR.ID = BCKP.FK_SRVR
WHERE SRVR.NM = #decServerName
CSV File Format
Import-Csv -Path C:\Bin\Repos\Backup.csv | C:\Bin\Scripts\update-serverbackuppath.ps1
Names Paths
Server1 \\fileshare\server_name
The Powershell code has several syntax errors, like referring to enums in erroneus a way:
# Incorrect form
[System.Data.Commandtype.StoredProcedure]
# Correct form for referring to enumeration
[System.Data.Commandtype]::StoredProcedure
Later on, there is an undeclared object which's member method is called:
# $command is not set, so ExecuteReader method is available
$reader = $command.ExecuteReader()
It is highly recommended to use strict mode in Powershell. It helps catching typos by preventing access to non-existing properties an uninitialized variables.
Edit
After the updated code, there are still two errors:
# This doesn't make sense. The variable should be SqlParameter, not SqlCommand
$ParamUpdateBackupPathServerName = New-Object -TypeName System.Data.SqlClient.SqlCommand
# Like so:
$ParamUpdateBackupPathServerName = New-Object -TypeName System.Data.SqlClient.SqlParameter
# This is nonsense syntax
$reader = New-Object -TypeName System.Data.SqlClient.SqlDataReader = $UpdateBackupPath.ExecuteReader()
# Like so:
$reader = $UpdateBackupPath.ExecuteReader()