DBA Audits with powershell

## open database connection
## Get Input from DBA, Reason for Login
<#
HealthCheck = 1
Maintenace = 2
Change Management = 3

#>
try
{

#Get Current user
$Currentuser = [Security.Principal.WindowsIdentity]::GetCurrent().Name
Write-Host $Currentuser

$DbaInput = “”
$Reason =””
$DbaInput = Read-Host -Prompt ‘Input your Reason for Login HealthCheck=1 Maintenace = 2 server Change Management = 3’
Write-Host “You input ‘$DbaInput’ ”

If($DbaInput -eq “1”) {$Reason = “HC”}
ElseIf($DbaInput -eq “2”){$Reason = “MT”}
ElseIf($DbaInput -eq “3”){$Reason = “CM”}
Else {“No Reason Found!”}
Write-Host “You input ‘$Reason’ ”

$conn = New-Object System.Data.SqlClient.SqlConnection(“Data Source=HARIERE-PC\SQLSERVER2014; Initial Catalog=BackupTest; Integrated Security=SSPI”)
$conn.Open()

$cmd = $conn.CreateCommand()
$cmd.CommandText =”INSERT INTO [dbo].[Reason_Login]
([Reason]
,[Name])
VALUES ( ‘ “+$Reason + ” ‘ “+”,'”+$Currentuser +” ‘)”
$cmd.ExecuteNonQuery()
$conn.Close()
}
catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Send-MailMessage -From hari@geek.Com -To hari@Geek.Com -Subject “DBA Loginreason Failed” -SmtpServer hari.geek.Com -Body ” failed $FailedItem. The error message was $ErrorMessage”
Break
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s