I am trying script out SQL Server Extended event Sessions of SQL Server 2012 using Power-Shell but I am unable to. Can you please help me. Thanks.
below code is what I have tried.
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Management.XEvent") | Out-Null
$cn = new-object System.Data.SqlClient.SqlConnection("Data Source=Sql2016;Integrated Security=SSPI;Initial Catalog=master");
$cn.Open()
$xEvents = New-Object Microsoft.SqlServer.Management.XEvent.event($cn)
$xEvents.Session | foreach {$_.Script()+";"}
$cn.Close()
Error:New-Object : Cannot find an overload for "Event" and the
argument count: "1"
Related
I searched around and found there is a way to get compatibility level of a database in powershell through something like:
Import-Module SqlServer
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$Server;Initial Catalog=$DB;Integrated Security=SSPI"
$conn = new-object Microsoft.SqlServer.Management.Common.ServerConnection($sqlConnection)
$srv = new-object Microsoft.SqlServer.Management.Smo.Server($conn)
$db = New-Object Microsoft.SqlServer.Management.Smo.Database
$db = $srv.Databases.Item("$DB")
$comp_lvl = New-Object Microsoft.SqlServer.Management.Smo.CompatibilityLevel
$comp_lvl = $db.CompatiblityLevel
Write-Host "Compatibility level =" $db.CompatibilityLevel
However, I am getting errors trying to get compatibility level of a database that is on an analysis server
Exception getting "Item": "Failed to connect to server ..."
I realized it is probably working for a regular database engine, but something else may be used for an analysis server. I looked around on MS Docs and didnt really find anything helpful.
SO is this even possible?
UPDATE:
I was able to find something on this page: https://technet.microsoft.com/en-us/hh213141(v=sql.100)
Import-Module SqlServer
$as = New-Object Microsoft.AnalysisServices.Server
$as.connect("$Server")
$as.databases
Write-Host "Compatibility level ="$as.DefaultCompatibilityLevel
but this returns ALL databases back...
I want to specify just one database to get the compatibility level of...
I tried this,
$as.databases["$Database"]
but it seems not to return the proper level, because the DB i am passing has a lvl of 1103, not 1200...
I figured it out!
Import-Module SqlServer
$as = New-Object Microsoft.AnalysisServices.Server
$as.connect("$Server")
$c = $as.Databases | Where-Object { $_.ID -eq $Database }
Write-Host "Compatibility level =" $c.CompatibilityLevel
What I'd like to do is execute two stored procedures from a PowerShell and save the results into a log file.
I have two procedures so I though it would be easier to create one "master" procedure which will execute the two procedures.
So far I was able to execute the master procedure successfully (both child procedures ran), but only the output from the second is stored in the log file.
param([string]$datein="string")
$OutputFile = "C:\...\ScriptOutput.txt"
$handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] {param($sender, $event) Out-File -filepath $OutputFile -inputobject $event.Message };
$SqlConnection = new-Object System.Data.SqlClient.SqlConnection("server=ServerName;database=DB;integrated security=true")
$SqlConnection.add_InfoMessage($handler);
$SqlConnection.FireInfoMessageEventOnUserErrors = $true;
$SqlConnection.Open() | Out-Null
# Execute procedures
$cmd = new-Object System.Data.SqlClient.SqlCommand("[dbo].[tst_master]", $SqlConnection)
$cmd.CommandType = [System.Data.CommandType]'StoredProcedure'
$cmd.Parameters.Add("#date_in",$datein) | Out-Null
$cmd.ExecuteNonQuery() | Out-Null
$SqlConnection.Close()
EDIT:
Its on virtual machine, Windows server 2016. Powershell version Major:5, Minor: 1. Im working with MSSQL 2014.
We use an Azure Elastic Pool resulting in multiple client databases and one master database with references to the client database.
We already have multiple databases and are working on a new version of the code. We use EF6 Code-First.
When we make a change to our model (add a property) we create the migration file and need to call Update-Database for all existing client databases.
This is monkey work we want to skip.
I already have a Powershell script to connect to the master database and execute a query on a table. This returns the names of the child databases.
With it I can change the Web.config and replace the Template database name with the proper name of the child database.
Now I need to call Update-Database to execute the migration scripts. With this last part I'm struggling because I'm running the ps1-script outside Visual Studio and thus the command Update-database is unknown. I tried using migrate.exe but then I get lots of errors.
I think the easiest solution is to run my script within the Package manager console but I can't figure out how to do that.
I managed to get it working. After I placed the ps1-file in the root of my code folder I could run it in the Package Manager Console using .\UpdateDatabases.ps1.
For completeness here's the script I created. I'm new to PowerShell so some optimizations might be possible.
cls
$currentPath = (Get-Item -Path ".\" -Verbose).FullName
#Read Web.config
$webConfig = $currentPath + "\<your project>\Web.config"
$doc = (Get-Content $webConfig) -as [Xml]
$DatabaseNamePrefix = $doc.configuration.appSettings.add | where {$_.Key -eq 'DatabaseNamePrefix'}
#Get Master connectionstring
$root = $doc.get_DocumentElement();
foreach($connString in $root.connectionStrings.add | where {$_.Name -eq "Master"})
{
$masterConn = $connString.connectionString
}
#Connect to master database
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $masterConn
#Query Client table for the child database names
$SqlQuery = "select Code from Clients"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
#Put query result in dataset
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
foreach ($row in $DataSet.Tables[0].Rows)
{
$clientDbName = $row[0].ToString().Trim()
#Change Web.Config
foreach($connString in $root.connectionStrings.add | where {$_.Name -eq "DevelopmentDb"})
{
$newDatabaseName = "Database=" + $DatabaseNamePrefix.value + $clientDbName + ";";
$newConn = $connString.connectionString -replace "(Database=.*?;)",$newDatabaseName
$connString.connectionString = $newConn;
}
$doc.Save($webConfig)
#Update database
Update-Database -ConfigurationTypeName Application
}
"Finished"
You may want to take a look at Azure Elastic Database Jobs. Which is designed to work with the elastic database pools.
The Elastic Database Jobs SDK includes also PowerShell components.
I am trying to find a solution to my problem online but no luck yet. Hence posting the question:
I am running a powershell script which will fetch backup details from all SQL Servers mentioned in a notepad. The script is working fine for SQL Servers till 2008R2. But I am getting error while connecting to SQL Server 2012/2014. The script is running on Windows Server 2008 having SQL Server 2008R2 installed on it. So I will request you to help me to troubleshoot it.
Input File:E:\Sachin\SQL_Servers2.txt
SERVERNAME,SERVERNAME,1433
$servers = Get-Content 'E:\Sachin\SQL_Servers2.txt'
#Create a new Excel object using COM
$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$Sheet = $Excel.Worksheets.Item(1)
#Counter variable for rows
$global:intRow = 1
foreach ($sv in $servers) {
# Separate the server and instance names
$srvr = $sv.Split(",")
$server = $srvr[0]
$instance = $srvr[1]
$port = $srvr[2]
getsqlinfo $server $instance $port
function getsqlinfo {
param (
[string]$svr,
[string]$inst,
[string]$port
)
foreach ($instancename in $inst)
{
#Create column headers
$Sheet.Cells.Item($intRow,1) = "INSTANCE NAME:"
$Sheet.Cells.Item($intRow,2) = $instancename
$Sheet.Cells.Item($intRow,1).Font.Bold = $True
$Sheet.Cells.Item($intRow,2).Font.Bold = $True
$global:intRow++
$Sheet.Cells.Item($intRow,1) = "DATABASE NAME"
$Sheet.Cells.Item($intRow,2) = "LAST FULL BACKUP"
$Sheet.Cells.Item($intRow,3) = "LAST DIFFERENTIAL BACKUP"
$Sheet.Cells.Item($intRow,4) = "FULL BACKUP AGE(DAYS)"
#Format the column headers
for ($col = 1; $col -le 4; $col++)
{
$Sheet.Cells.Item($intRow,$col).Font.Bold = $True
$Sheet.Cells.Item($intRow,$col).Interior.ColorIndex = 48
$Sheet.Cells.Item($intRow,$col).Font.ColorIndex = 34
}
$global:intRow++
#######################################################
#This script gets SQL Server database information using PowerShell
$ConnectionString = "data source = $inst,$port; initial catalog = master; trusted_connection = true;"
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
# Create an SMO connection to the instance
$s = New-Object ('Microsoft.SqlServer.Management.Smo.Server')
$s.ConnectionContext.ConnectionString = $ConnectionString
$dbs = $s.Databases
#Formatting using Excel
ForEach ($db in $dbs)
Error Msg:
The following exception was thrown when trying to enumerate the collection: "Failed to connect to server .".
At E:\sachin\BackupDetailsVersion7.ps1:51 char:8
+ ForEach <<<< ($db in $dbs)
+ CategoryInfo : NotSpecified: (:) [], ExtendedTypeSystemException
+ FullyQualifiedErrorId : ExceptionInGetEnumerator
Pre-Checks Done:
I am able to telnet the target SQL Server from the Server where I am running the script.
I am having access to the target SQL Server as well.
Microsoft® Windows PowerShell Extensions for Microsoft® SQL Server® 2012 SP2,Microsoft® SQL Server® 2012 SP2 Shared Management Objects and Microsoft® System CLR Types for Microsoft® SQL Server® 2012 SP2 are already installed on the target Server.
Execution policy is set to unrestricted on the target Server.
I am able to get the SQL Server details on the target machine when checking locally, but not able to get details from other machine.
I am suspecting whether is there any restriction/limitation to connect between different SQL Server versions through powershell (any kind of compatibility issue).
Any help/suggestions will be highly appreciated. Thanks in advance. :)
has anyone tried configuring SQL Server Facets using powershell... i tried with below code..and i am able to find out properties of the Facets but not getting idea on how to set values to these properties.
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Dmf') | Out-Null
[System.Reflection.Assembly]::LoadWithPartialNam('Microsoft.SQLServer.Management.Sdk.Sfc') | Out-Null
$conn = New-Object Microsoft.SQlServer.Management.Sdk.Sfc.SqlStoreConnection("server='Ramu-pc';Trusted_Connection=true")
$PolicyStore = New-Object Microsoft.SqlServer.Management.DMF.PolicyStore($conn)
$facets = [Microsoft.SqlServer.Management.Dmf.PolicyStore]::Facets | Where {$_.Name -eq 'ISurfaceAreaFacet'}
$facets | Format-Table –Auto
when i execute below command, i see different methods but i am not getting help on how to user those methods.
$Facets | gm
i need to configure below values in the above Facet:
AdHocRemoteQueriesEnabled = True
xp_cmdshell = true
While it's not exactly using what you show but here's what I use.
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Null
$server = New-Object 'Microsoft.SqlServer.Management.SMO.Server' ('Ramu-pc')
$server.Configuration.AdHocDistributedQueriesEnabled.ConfigValue = 1
$server.Configuration.XPCmdShellEnabled.ConfigValue = 1
$server.Configuration.Alter()
You can automate with normal batch and sp_configure
I hope this helps someone find an answer while automating setting up facets, it would have saved me some time.
Replace AdHocRemoteQueriesEnabled for your answer instead of my working example below "remote access".
Similar to you I was looking for a way to automate, my case was RemoteAccessEnabled instead of installing the manager on any target
machine I wanted to setup as a master. The above special keyword didn't even register in a search.
sp_configure Transact-SQL statement:
exec sp_configure "remote access", 1
also:
remote query timeout
remote proc trans
HTH someone