0% found this document useful (0 votes)
31 views6 pages

Powershell cluster verification

This document outlines a PowerShell script developed to verify the status of SQL Server instances, ensuring they are running correctly. It includes functionalities for logging, sending email notifications, and managing directories and files related to the logs. The script supports SQL Server 2005 and later versions, with a focus on checking the master and tempdb databases' statuses.

Uploaded by

Murali Pujari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views6 pages

Powershell cluster verification

This document outlines a PowerShell script developed to verify the status of SQL Server instances, ensuring they are running correctly. It includes functionalities for logging, sending email notifications, and managing directories and files related to the logs. The script supports SQL Server 2005 and later versions, with a focus on checking the master and tempdb databases' statuses.

Uploaded by

Murali Pujari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

#region Script version details

## Verify all sql server status


## Devloped By - Jayvant Patel, Datavail Corporation
## Modified By - Darshan Bharnuke, Datavail Corporation
## Latest Script Version = PSS Ver 1.0.0, Releae Dt: 2018/04/10
## Supported SQL Version : SQL 2005 and later.
## Version History
## PSS Ver 1.0.0 - it will open/close the on master and tempdb database
to ensure SQL server is up and running fine -> Jayvant Patel , Datavail
Corporation
#endregion

#region manage "RunAsAdministartor"


If (-NOT ([Security.Principal.WindowsPrincipal]
[Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.Wi
ndowsBuiltInRole] "Administrator"))
{
#"No Administrative rights, it will display a popup window asking user
for Admin rights"

$arguments = "& '" + $myinvocation.mycommand.definition + "'"


Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList
$arguments

break
}
#endregion

#region import assembly and basic dir and file settings


if( !(Get-Module | where {$_.name -eq 'sqlps'}))
{
Import-Module 'sqlps' �DisableNameChecking
}

$MyInvocation = (Get-Variable MyInvocation).Value


$GlobalPath = Split-Path $MyInvocation.MyCommand.Path
$Servers = "$globalPath\servers.txt"

$file= Get-Date -format "yyyyMMdd"


$file = "Log_"+$file+".txt"

$LogDir = "$GlobalPath\Log"
$LogFile = $LogDir+"\"+$file

#endregion

#region smtp srv and recpt details


$mailsmtphost = "mail.lnc.com"
$frm = "[email protected]"
$recpt = "[email protected]"
$cc = "[email protected]"

#endregion

#region function to create new dir or file

Function CreateDirorFile
{
param($Path, $Type)
$Path = $Path.replace("""","")

## Create folder or file if not exists


if ($Type -eq "F")
{

$DoesFileExist = Test-Path Microsoft.PowerShell.Core\


FileSystem::$Path
$null = if (!$DoesFileExist){New-Item
Microsoft.PowerShell.Core\FileSystem::$Path -ItemType file}

}
else
{

$DoesFolderExist = Test-Path Microsoft.PowerShell.Core\


FileSystem::$Path
$null = if (!$DoesFolderExist){MKDIR Microsoft.PowerShell.Core\
FileSystem::$Path}
}
}

## Create Log folder if not exists


CreateDirorFile $LogDir "D"

## Create Logfile dir if not exists


CreateDirorFile $LogFile "F"

# Delete files older than the $retention.


$LogLoc = $LogDir+"\Log*.txt"
$retention = 30
Get-ChildItem -Path $LogDir -Recurse -force -ErrorAction SilentlyContinue |
where {$_.LastwriteTime -lt (Get-Date).AddDays(-$retention) } |Remove-Item -Force
-ErrorAction SilentlyContinue

#endregion

#region supprotive functions

Function WriteLog
{

param([string]$LogComment)
$now=Get-Date -format "dd-MMM-yyyy HH:mm:ss"
Add-Content $Logfile "$now -> $LogComment"

Function sendEmail
{
param($from,$to,$subject,$smtphost,$body,$cc)
# $body = "Kindly find Monthly Patching verification Report."
$smtp= New-Object System.Net.Mail.SmtpClient $smtphost
$msg = New-Object System.Net.Mail.MailMessage $from, $to, $subject, $body
$msg.cc.add($cc)
$msg.isBodyhtml = $false
$msg.Priority = "High"
#$msg.Attachments.Add($Attachments)

# Foreach ($a in $Attachments){


# $attachment = New-Object System.Net.Mail.Attachment $a
# $msg.Attachments.Add($attachment)
#}

$smtp.send($msg)
}

#endregion

#region process initiating...


Add-Content $Logfile " "
Add-Content $Logfile " "
$processdt=Get-Date -format "dd-MMM-yyyy"
WriteLog "************************** $processdt **************************"
WriteLog "Process started"

$errorflag = 0

#endregion

#region checking all server status

#Load the SQL Server SMO Assemly


#[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") |
Out-Null

#Create a new SqlConnection object


#$objSQLConnection = New-Object System.Data.SqlClient.SqlConnection

$content = Get-Content $Servers

#$arrError = @()

foreach ($line in $content)


{
#if ($line -ne "Server|Instance|IsEnabled")
if ($line -ne "Instance|IsEnabled")
{
##$Server,$Instance,$IsEnabled = $line.split("|",3)
##$Server = $Server.trim()
$Instance,$IsEnabled = $line.split("|",2)
$Instance = $Instance.trim()
$IsEnabled = $IsEnabled.trim()

if($IsEnabled -eq "Y" -and $Instance.Trim() -ne "")


{
Try
{

##1 Checking master db status


WriteLog "Checking $Instance running on which node..."
Write-Host "Checking $Instance running on which node..."
Invoke-Sqlcmd -ServerInstance $Instance -Database master -
Query "
If (SELECT SERVERPROPERTY('IsClustered'))=1
BEGIN TRY
declare @Node varchar(100) Set @Node=convert
(varchar(max),serverproperty('ComputerNamePhysicalNetBIOS'))
If (select right (@Node,1))='1'
RAISERROR ('SQL server is running on wrong node. Please failback to original
node', -- Message text.
16, -- Severity.
1 -- State.
);
Else
Print 'SQL Server is running on correcrt node.'
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;

SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();

-- Use RAISERROR inside the CATCH block to return error


-- information about the original error that caused
-- execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
);
END CATCH;
Else
Print 'SQL Server is not clustered'
go
If SERVERPROPERTY ('IsHadrEnabled') = 1
BEGIN TRY
declare @Node1 varchar(100)
select @Node1= replica_server_name from (SELECT
ar.replica_server_name,
ag.name AS ag_name,
adc.database_name,
CASE WHEN hags.primary_replica = ar.replica_server_name THEN 'Yes' ELSE 'No' END AS
is_primary_replica,
drs.synchronization_state_desc,
drs.synchronization_health_desc
FROM sys.dm_hadr_database_replica_states AS drs
INNER JOIN sys.availability_databases_cluster AS adc
ON drs.group_id = adc.group_id AND
drs.group_database_id = adc.group_database_id
INNER JOIN sys.availability_groups AS ag
ON ag.group_id = drs.group_id
INNER JOIN sys.availability_replicas AS ar
ON drs.group_id = ar.group_id AND
drs.replica_id = ar.replica_id
INNER JOIN sys.dm_hadr_availability_group_states AS hags
ON hags.group_id = ag.group_id
)a where a.is_primary_replica='Yes'
Print @Node1
If (select right (@Node1,1))='1'
RAISERROR ('Always On is running on wrong Replica. Please failback
immediately', -- Message text.
16, -- Severity.
1 -- State.
);
Else
Select 'Always On is running on correct Replica'
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;

SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();

-- Use RAISERROR inside the CATCH block to return error


-- information about the original error that caused
-- execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
);
END CATCH;

Else
Print 'No AlwaysOn'
" -ErrorAction Stop
Write-Host "Eveything looks good on the server."
WriteLog "Eveything looks good on the server.."

##2 Checking tempdb status


WriteLog "Checking tempdb database connection on
$Instance..."
Write-Host "Checking tempdb database connection on
$Instance..."
Invoke-Sqlcmd -ServerInstance $Instance -Database master -
Query "select GetDt into #tmpGetDt from (Select getdate() as GetDt) as qry" -
ErrorAction Stop
Write-Host "SQL Server is UP and running."
WriteLog "SQL Server is UP and running."

write-host " "


}

Catch
{

$CaughtException = "Caught an exception:"


$ExceptionType = "$($_.Exception.GetType().FullName)"
$ExceptionMessage = "$($_.Exception.Message)"

WriteLog $CaughtException
WriteLog $ExceptionType
WriteLog $ExceptionMessage

write-host "$CaughtException" -ForegroundColor Red


write-host "$ExceptionType" -ForegroundColor Red
write-host "$ExceptionMessage" -ForegroundColor Red

$emailSub = "LFG: P1 - $instance not running on preferred


node."

$emailBody = "Hello Team,

$instance is not running on preferred node. Please look into it ASAP.

Thanks,
Datavail Corporation."

sendEmail $frm $recpt $emailSub $mailsmtphost $emailBody $cc

#$arrError += [pscustomobject]@{Server = $Server; Instance =


$Instance ; ExceptionType=$ExceptionType;ExceptionMessage=$ExceptionMessage}

continue
}

WriteLog "*********Process Ended**********"

#endregion

You might also like