Good morning, Clarify first that the script works, but surely among all of you help me to optimize it.
This is a script that extracts security events (Logon / Logoff from the machine) and stores them in a SQL database. Here goes:
'
Set the variables for connection to the database:
$SQLServer = "DatabaseServer.contoso.com"
$SQLDBName = "SQLEvents"
$SQLTable = "Events"
$uid = "DBUser"
$pwd = "pass@word1"
Stores in a variable the list of events related to the Logon / Logoff of users:
$list = get-EventLog Security -Source Microsoft-Windows-Security-Auditing | Where { $_.InstanceID -like "4624" -or $_.InstanceID -like "4625" -or $_.InstanceID -like "4647"} | Select MachineName,Index,TimeGenerated,EntryType,Source,InstanceId,Message
write-host "Numero de eventos en el log: $($list.count)"
Establish the connection to the database:
$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = False; User ID = $uid; Password = $pwd;"
$conn.open()
$cmd = New-Object System.Data.SqlClient.SqlCommand
$cmd.connection = $conn
For each element in the variable, set the values to insert in the database:
foreach ($item in $list) {
$computer_id = $item.MachineName
$num = $item.Index
$time = get-date $item.TimeGenerated -Format s
$entrytype = $item.EntryType
$source = $item.Source
$instanceid = $item.InstanceId
$message = $item.Message
# Lanza la consulta y evita los duplicados en función del "Index" y el nombre de la máquina "MachineName".
# Al evitar duplicados, podemos almacenar en una misma tabla los registros de múltiples servidores.
$cmd.commandtext = "IF NOT EXISTS (SELECT 1 FROM $SQLTable WHERE [num] = '$num' AND [computer_id] = '$computer_id') INSERT INTO $SQLTable (computer_id,num,time,entrytype,Source,instanceid,message) VALUES ('$computer_id','$num','$time','$entrytype','$source','$instanceid','$message')"
$cmd.executenonquery()
}
Close the connection with the DB:
$conn.close()
'
One of the things that is about to be done is to mask the user and the password (encrypt it, go). And another: Is it possible to take a small summary (Single Line) of the number of records inserted in the database for each execution? I want to export it to a local log in the machine (c: \ Temp \ log.txt), but even though I have "saved" the script I have not managed to do anything without affecting the speed of execution ...
Thank you very much from now!
Regards, Klemin