Hello All,
A strange request.
We are running multiple always on servers.
Backups takes place on secondary replica of always on server.
I need to create a report in powershell or t-sql that would identify secondary replica and verify backup status.
DM1-- instance name
M1-- primary instance
M2 --secondary instance
$sqlservers = @(
'DM1',
'M2',
'M3')
$dbrecords = @() ## array for query results
Foreach($server in $sqlservers) {
$dbrecords += invoke-sqlcmd -query 'DROP TABLE IF EXISTS #mysgbackupstatus1;
DROP TABLE IF EXISTS ##mysgbackupstatus;
CREATE TABLE #mysgbackupstatus1(
replica_server_name nvarchar(256),
role_desc nvarchar(60))
-----below query writing only secondary replica to #mysgbackupstatus1 table
INSERT INTO #mysgbackupstatus1 (replica_server_name, role_desc)
SELECT replica_server_name
from sys.dm_hadr_availability_replica_states as ha
inner join sys.availability_replicas as a on ha.replica_id=a.replica_id
WHERE role_desc = ''SECONDARY'';
Each row in #mysgbackupstatus represents secondary SQL instance.
I am failing here as I do not know how to connect to SQL instance by fetching row from #mysgbackupstatus
once connected I am planning to run below CTE into a CSV file.
$dbrecords += invoke-sqlcmd -query ';with backup_cte as( select database_name, backup_type = case type when ''D'' then ''database'' when ''L'' then ''log'' when ''I'' then ''differential'' else ''other'' end, backup_finish_date, rownum = row_number() over ( partition by database_name, type order by backup_finish_date desc ) from msdb.dbo.backupset)' -ServerInstance $server}$dbrecords | Export-Csv "C:\Temp\SQLOutput.csv"## $dbrecords | Out-GridView
I am messed up and do not know if what I am talking is feasible or not.
Please help and guide.
I am rookie in world of development.
Thank you in advance.