Azure Monitoring Database performance - azure-sql-database

I need to compile the following information: "a scheduled report that shows the DB environment state. From free space to performance, failed jobs and anything else that can cause a DB not to function correctly."
I keep getting referred to the same learn.microsoft links but for some reason i just get progressively more confused.
Can someone please help me with a step by step instruction on how to achieve the above mentioned?
All our DBs are on Azure VMs.
I tried Chat GPT for the disk sizes and it gave me a Power Shell code. <
# Connect to your Azure account
Connect-AzAccount
# Get a list of all virtual machines in your subscription
$vms = Get-AzVM
# Loop through the list of virtual machines
foreach ($vm in $vms) {
# Get the details of each virtual machine
$vmName = $vm.Name
$vmSize = $vm.HardwareProfile.VmSize
# Get a list of all disks attached to the virtual machine
$disks = Get-AzDisk | Where-Object { $_.ManagedBy -eq $vm.Id }
# Loop through the list of disks
foreach ($disk in $disks) {
# Get the details of each disk
$diskName = $disk.Name
$diskSize = $disk.DiskSizeGB
$diskType = $disk.StorageAccountType
# Print the virtual machine, disk, and disk size information
Write-Output "VM Name: $vmName"
Write-Output "VM Size: $vmSize"
Write-Output "Disk Name: $diskName"
Write-Output "Disk Size: $diskSize GB"
Write-Output "Disk Type: $diskType"
Write-Output ""
}
}
\>
I could not get free space information or Database information this way.

Your script is working but you are retrieving information about the VMs, not about the SQL Server that is stored within the VMs.
You need to login into the SQL Server inside the VM and run the query that you want:
# Load the Azure RM module
Import-Module AzureRM
# Login to Azure
Login-AzureRmAccount
# Get a list of all Azure VMs
$vms = Get-AzureRmVM
# Loop through each VM
foreach ($vm in $vms) {
# Get the VM's IP address
$ipAddress = (Get-AzureRmPublicIpAddress -ResourceGroupName $vm.ResourceGroupName -Name ($vm.Name + '-ip')).IpAddress
# Connect to SQL Server on the VM
$connectionString = "Server=$ipAddress;Database=master;User ID=<username>;Password=<password>"
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
$connection.Open()
# Execute the SELECT ##VERSION query
$command = $connection.CreateCommand()
$command.CommandText = "SELECT ##VERSION"
$reader = $command.ExecuteReader()
# Display the result
while ($reader.Read()) {
Write-Output $reader.GetValue(0)
}
# Close the connection
$connection.Close()
}
Note that you will need to replace <username> and <password> with the actual SQL Server login credentials for each VM.
Replace the "SELECT ##VERSION" with the query that investigates:
DB environment state
free space
performance
failed jobs
anything else...

Related

virtual network service endpoint

I have a virtual network in my resource group with the default subnet Microsoft Storage Service endpoints are already assigned to the default subnet of the virtual network but, now I want to add another multiple service endpoint with default subnet using PowerShell
The code below is what I'm using to add the service endpoint Microsoft.ServiceBus to the same virtual network.
#Get vnet
$virtualnetwork = Get-AzureRmVirtualNetwork -Name $VN -ResourceGroupName $RG
#Configure service endpoint
Add-AzureRmVirtualNetworkSubnetConfig -Name $SN -AddressPrefix $SAP -
VirtualNetwork $virtualnetwork -ServiceEndpoint $EP
#Set configuration
$virtualnetwork | Set-AzureRmVirtualNetwork
The issue is that every time I run the above script, it updates the current service endpoint rather than adding a new one. Any idea
I tried to reproduce the same in my environment and added the service endpoint successfully like below.
I have created microsoft.storage service endpoint with default subnet like Below.
I tried to add another service endpointMicrosoft.ServiceBus to the same virtual network with default subnet using below powershell script
$subscription = "ID"
$subnets = #('default')
$vnetName = "your vnetname"
$vnetRgName = "Rgname"
$newEndpoint = "Microsoft.ServiceBus"
Set-AzContext -Subscription $subscription
foreach($snet in $subnets){
Write-Host "Modifying Service Endpoints for subnet: $snet" -fore red -back white
$virtualNetwork = Get-AzVirtualNetwork -Name $vnetName -ResourceGroupName $vnetRgName | Get-AzVirtualNetworkSubnetConfig -Name $snet
$addrPrefix = $virtualNetwork.AddressPrefix
#Get existing service endpoints
$ServiceEndPoint = New-Object 'System.Collections.Generic.List[String]'
$virtualNetwork.ServiceEndpoints | ForEach-Object { $ServiceEndPoint.Add($_.service) }
if ($ServiceEndPoint -notcontains $newEndPoint){
$ServiceEndPoint.Add($newEndpoint)
}
$delegation=$virtualNetwork.Delegations
#Add new service endpoint
Get-AzVirtualNetwork -Name $vnetName -ResourceGroupName $vnetRgName | Set-AzVirtualNetworkSubnetConfig -Name $snet -AddressPrefix $addrPrefix -ServiceEndpoint $ServiceEndPoint -Delegation $delegation | Set-AzVirtualNetwork
}
Output:
To check in portal, Microsoft.serviceBus is added successfully with default subnet along with Microsoft.storage.

Azure Backup. Wait Only Until Snapshot Is Taken, Not Until It's Transferred to Vault

I'm writing a PowerShell script for starting MySQL Server process, initiating backups from Azure Recovery Services, then starting MySQL Server process again.
For my purposes Wait-AzRecoveryServicesBackupJob cmdlet is not suitable, as Azure Backup always takes 10 minutes to take a snapshot and takes 3-24 hours to transfer that snapshot to Vault. How can I wait only until snapshot is taken?
You will need to set up your own polling loop, but unfortunately the Get-AzRecoveryServicesBackupJob doesn't have the properties you need. There are two options available to you in Powershell-- the REST API or the CLI.
Once you've gotten the job info, you can find the individual tasks under properties.extendedInfo.tasksList
Implementing this under the CLI would look something like this:
$resourceGroup = "resourceGroup"
$vaultName = "vaultName"
$jobs = az backup job list --resource-group $resourceGroup --vault-name $vaultName --start-date 28-8-2020 | convertfrom-json
$jobName = $jobs[0].name
$jobStatus = az backup job show --name $jobName --resource-group $resourceGroup --vault-name $vaultName
$taskStatus = $jobStatus.properties.extendedInfo.tasksList | Where-Object { $_.taskId -eq "Take Snapshot"}
While ( $taskStatus.status -ne Completed ) {
Write-Host -Object "Waiting for completion..."
Start-Sleep -minutes 1
$jobStatus = az backup job show --name $jobName --resource-group $resourceGroup --vault-name $vaultName
$taskStatus = $jobStatus.properties.extendedInfo.tasksList | Where-Object { $_.taskId -eq "Take Snapshot"}
}
Write-Host -Object "Done!"

Setup Alert when SQL Agent Down using Task Scheduler

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.

Powershell SMO Can't Connect

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.

Network error on powershell SQL job step

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.