I'm newbie here and would like to ask for your help writing a powershell script and if possible to create a detection/remediation Powershell script for local admin computer.
I have created a local user administrator and password to all our computers and my objective is to create a script that will notify me when someone tries or change the password of the local admin. I tried this script below but seems not doing what I expect.
# This script is intended to create a custom local administrator for offline use on Entra ID joined computers.
# Define the username and password
$Username = "OfflineAdmin"
$Password = "pppppp"
# Check if the user already exists
$ExistingUser = Get-LocalUser -Name $Username -ErrorAction SilentlyContinue
if ($ExistingUser) {
"The user exists."
# If the user exists, update the password and set it to never expire
Set-LocalUser -Name $Username -Password (ConvertTo-SecureString -AsPlainText $Password -Force) -PasswordNeverExpires $true
} else {
"Adding the user."
# If the user doesn't exist, create the local user and set the password to never expire
New-LocalUser -Name $Username -Password (ConvertTo-SecureString -AsPlainText $Password -Force) -PasswordNeverExpires
# Then add the new user to the local administrators group
$AdminGroup = Get-LocalGroup -Name "Administrators"
$AdminUser = Get-LocalUser -Name $Username
Add-LocalGroupMember -Group $AdminGroup -Member $AdminUser
}
Stop-Transcript
# Define the event log properties when someone change the password
$LogName = "Security"
$EventID = 4738 # Event ID for a user account was changed (password change)
# Specify the email details
$EmailFrom = "[email protected]"
$EmailTo = "[email protected]"
$Subject = "Local Admin Password Change Notification"
$SMTPServer = "smtp-mail.outlook.com"
# Get the latest event from the Security log
$latestEvent = Get-WinEvent -LogName $LogName -FilterXPath "*[System[(EventID=$EventID)]]" | Select-Object -First 1
# Check if the event is not null (i.e., a password change event is found)
if ($latestEvent -ne $null) {
# Extract relevant information from the event
$EventTime = $latestEvent.TimeCreated
$Username = $latestEvent.Properties[0].Value
$ComputerName = $latestEvent.Properties[1].Value
# Compose the email body
$Body = "Local admin password changed on $ComputerName.`r`n`r`n"
$Body += "Username: $Username`r`n"
$Body += "Event Time: $EventTime`r`n"
# Send the email
Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $Subject -Body $Body -SmtpServer $SMTPServer
} else {
Write-Host "No password change events found."
}