0% found this document useful (0 votes)
11 views

Active Directory Useful Powershell Commands and Scripts 1739748834

The document provides a comprehensive list of 50 essential PowerShell commands for managing Active Directory, Group Policy, DNS, DHCP, and Windows Server from 2016 to 2022. It includes detailed scripts for automating tasks such as user creation, disabling inactive accounts, and backing up Group Policy Objects. Additionally, it outlines steps for scheduling these scripts using Task Scheduler to enhance administrative efficiency.

Uploaded by

Erico Belem
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Active Directory Useful Powershell Commands and Scripts 1739748834

The document provides a comprehensive list of 50 essential PowerShell commands for managing Active Directory, Group Policy, DNS, DHCP, and Windows Server from 2016 to 2022. It includes detailed scripts for automating tasks such as user creation, disabling inactive accounts, and backing up Group Policy Objects. Additionally, it outlines steps for scheduling these scripts using Task Scheduler to enhance administrative efficiency.

Uploaded by

Erico Belem
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Managing and maintaining Active Directory

(AD) and Windows Server 2016–2022 requires a


variety of PowerShell commands, scripts, and
administrative tools. Below is a list of the 50 most
commonly used commands grouped by their
function.
1. Active Directory User Management
1. Get-ADUser -Filter * - List all users in the
domain.
2. New-ADUser -Name "John Doe"
-SamAccountName jdoe -UserPrincipalName
[email protected] -Path
"OU=Users,DC=domain,DC=com" -Enabled
$true - Create a new AD user.
3. Set-ADUser -Identity jdoe -Title "IT
Manager" - Modify a user’s attributes.
4. Disable-ADAccount -Identity jdoe -
Disable a user account.
5. Enable-ADAccount -Identity jdoe - Enable
a disabled user account.
6. Unlock-ADAccount -Identity jdoe -
Unlock a locked-out user account.
7. Move-ADObject -Identity "CN=John
Doe,OU=OldOU,DC=domain,DC=com"
-TargetPath
"OU=NewOU,DC=domain,DC=com" - Move
a user to a different OU.
8. Remove-ADUser -Identity jdoe -Confirm:
$false - Delete a user account.
9. Set-ADUser -Identity jdoe
-ChangePasswordAtLogon $true - Force a
user to change their password at next login.
10. Get-ADUser -Filter {LockedOut -eq
$true} - Find all locked-out users.
2. Active Directory Group
Management
11. Get-ADGroup -Filter * - List all AD
groups.
12. New-ADGroup -Name "ITAdmins"
-GroupScope Global -GroupCategory
Security - Create a new security group.
13. Add-ADGroupMember -Identity
"ITAdmins" -Members jdoe - Add a user to a
group.
14. Remove-ADGroupMember -Identity
"ITAdmins" -Members jdoe -Confirm:$false -
Remove a user from a group.
15. Get-ADGroupMember -Identity
"ITAdmins" - List members of a group.
16. Set-ADGroup -Identity "ITAdmins"
-Description "IT Department Administrators"
- Modify a group’s properties.
17. Remove-ADGroup -Identity "ITAdmins" -
Delete a group.
3. Active Directory Computer
Management
18. Get-ADComputer -Filter * - List all
computers in AD.
19. New-ADComputer -Name "PC-001" -Path
"OU=Computers,DC=domain,DC=com" -
Add a new computer to AD.
20. Remove-ADComputer -Identity "PC-001"
- Remove a computer from AD.
21. Enable-ADAccount -Identity "PC-001" -
Enable a computer account.
22. Disable-ADAccount -Identity "PC-001" -
Disable a computer account.
23. Get-ADComputer -Filter
{OperatingSystem -like "*Windows 10*"} -
Find all Windows 10 computers.
4. Active Directory Organizational
Unit (OU) Management
24. Get-ADOrganizationalUnit -Filter * - List
all OUs.
25. New-ADOrganizationalUnit -Name "HR"
-Path "DC=domain,DC=com" - Create a new
OU.
26. Remove-ADOrganizationalUnit -Identity
"OU=HR,DC=domain,DC=com" -Confirm:
$false - Delete an OU.
27. Set-ADOrganizationalUnit -Identity
"OU=HR,DC=domain,DC=com"
-ProtectedFromAccidentalDeletion $false -
Modify OU properties.
28. Move-ADObject -Identity "CN=John
Doe,OU=Users,DC=domain,DC=com"
-TargetPath "OU=HR,DC=domain,DC=com"
- Move an object to another OU.
5. Group Policy Management
29. Get-GPO -All - List all Group Policy
Objects (GPOs).
30. New-GPO -Name "SecurityPolicy" -
Create a new GPO.
31. Remove-GPO -Name "SecurityPolicy" -
Delete a GPO.
32. Get-GPResultantSetOfPolicy -Computer
PC-001 -User jdoe - Get applied GPOs for a
user/computer.
33. Import-GPO -BackupGpoName
"OldPolicy" -TargetName "NewPolicy" -
Restore a GPO from backup.
34. Set-GPLink -Name "SecurityPolicy"
-Target "OU=IT,DC=domain,DC=com"
-Enforced Yes - Link a GPO to an OU.
6. DNS and DHCP Management
35. Get-DnsServerZone - List all DNS zones.
36. Add-DnsServerResourceRecordA -Name
"web" -ZoneName "domain.com"
-IPv4Address "192.168.1.10" - Add an A
record.
37. Remove-DnsServerResourceRecord
-ZoneName "domain.com" -Name "web"
-RecordType A - Delete a DNS record.
38. Get-DhcpServerv4Scope - List all DHCP
scopes.
39. Add-DhcpServerv4Scope -Name
"MainScope" -StartRange 192.168.1.100
-EndRange 192.168.1.200 -SubnetMask
255.255.255.0 -State Active - Create a DHCP
scope.
40. Remove-DhcpServerv4Scope -ScopeId
192.168.1.0 -Confirm:$false - Delete a DHCP
scope.
7. Windows Server Management
41. Get-Service - List all services on the
server.
42. Restart-Service -Name "Spooler" - Restart
a service.
43. Get-EventLog -LogName System -Newest
50 - View recent system logs.
44. Get-Process - List all running processes.
45. Stop-Process -Name "notepad" - Kill a
process.
46. Get-NetIPAddress - Display network
settings.
47. Test-NetConnection -ComputerName
google.com -Port 443 - Test internet
connectivity.
48. Restart-Computer -Force - Restart the
server.
49. Stop-Computer -Force - Shutdown the
server.
50. Install-WindowsFeature -Name AD-
Domain-Services -IncludeManagementTools
- Install Active Directory on a server.
Conclusion

These 50 essential PowerShell commands help


in managing Active Directory, Group Policy,
DNS, DHCP, and Windows Server services
efficiently. Would you like detailed scripts for
automation?

Here are PowerShell scripts to help automate key


tasks for Active Directory (AD) and Windows
Server 2016-2022 management. These scripts
cover user management, group policy, DNS,
DHCP, and server maintenance.
1. Bulk User Creation from CSV
This script creates multiple users in Active
Directory from a CSV file.
CSV Format (users.csv)
FirstName,LastName,UserName,OU,Password
John,Doe,jdoe,OU=Users,DC=domain,DC=com,Pa$$w0rd!
Jane,Smith,jsmith,OU=Users,DC=domain,DC=com,Pa$$w0rd!

PowerShell Script
Import-Module ActiveDirectory

$users = Import-Csv "C:\Scripts\users.csv"

foreach ($user in $users) {


$SecurePassword = ConvertTo-SecureString
$user.Password -AsPlainText -Force
New-ADUser -GivenName $user.FirstName -Surname
$user.LastName -SamAccountName $user.UserName `
-UserPrincipalName "$
($user.UserName)@domain.com" -Path $user.OU
-AccountPassword $SecurePassword `
-Enabled $true
Write-Host "Created User: $($user.UserName)"
}

2. Find and Disable Inactive AD Users


This script finds users inactive for 90+ days and
disables them.
$DaysInactive = 90
$Date = (Get-Date).Adddays(-$DaysInactive)

$Users = Get-ADUser -Filter {LastLogonDate -lt $Date


-and Enabled -eq $true} -Properties LastLogonDate
foreach ($User in $Users) {
Disable-ADAccount -Identity $User.SamAccountName
Write-Host "Disabled: $($User.SamAccountName)"
}

3. Export AD Users and Groups to


CSV
This script exports all users and their group
memberships.
$Users = Get-ADUser -Filter * -Property MemberOf |
Select-Object SamAccountName, DisplayName, MemberOf
$Users | Export-Csv "C:\Scripts\AD_Users.csv"
-NoTypeInformation
Write-Host "Exported AD users to C:
\Scripts\AD_Users.csv"

4. Create and Link a Group Policy


Object (GPO)
This script creates a GPO and links it to an OU.
$GPOName = "SecurityPolicy"
$OU = "OU=IT,DC=domain,DC=com"

New-GPO -Name $GPOName | New-GPLink -Target $OU


-Enforced Yes
Write-Host "Created and linked GPO: $GPOName to $OU"
5. Backup and Restore Group Policy
Objects

Backup All GPOs


Backup-GPO -All -Path "C:\GPOBackups"
Write-Host "Backup completed at C:\GPOBackups"

Restore a GPO
Import-GPO -BackupGpoName "SecurityPolicy" -TargetName
"RestoredPolicy" -Path "C:\GPOBackups"
Write-Host "Restored GPO from backup"

6. Create an AD Group and Add Users


This script creates a security group and adds
users.
$GroupName = "ITAdmins"
$Users = @("jdoe", "jsmith")

New-ADGroup -Name $GroupName -GroupScope Global


-GroupCategory Security
foreach ($User in $Users) {
Add-ADGroupMember -Identity $GroupName -Members
$User
Write-Host "Added $User to $GroupName"
}

7. Get All Locked Out Users


Get-ADUser -Filter {LockedOut -eq $true} | Select
SamAccountName, Name

8. Reset a User’s Password


$User = "jdoe"
$NewPassword = ConvertTo-SecureString "NewP@ssword123"
-AsPlainText -Force
Set-ADAccountPassword -Identity $User -NewPassword
$NewPassword -Reset
Write-Host "Password reset for $User"

9. List All Computers in AD


Get-ADComputer -Filter * | Select Name,
OperatingSystem, LastLogonDate

10. Restart All Domain Controllers


This script finds all DCs and reboots them.
$DCs = Get-ADDomainController -Filter *
foreach ($DC in $DCs) {
Restart-Computer -ComputerName $DC.HostName -Force
Write-Host "Restarted $($DC.HostName)"
}

11. Export DNS Records to CSV


Get-DnsServerResourceRecord -ZoneName "domain.com" |
Export-Csv "C:\Scripts\DNSRecords.csv"
-NoTypeInformation
Write-Host "Exported DNS records"
12. Create a New DHCP Scope
$ScopeID = "192.168.1.0"
$StartIP = "192.168.1.100"
$EndIP = "192.168.1.200"
$SubnetMask = "255.255.255.0"

Add-DhcpServerv4Scope -Name "MainScope" -StartRange


$StartIP -EndRange $EndIP -SubnetMask $SubnetMask
-State Active
Write-Host "Created DHCP Scope"

13. List Active Services on a Server


Get-Service | Where-Object {$_.Status -eq "Running"}

14. Restart a Service on Multiple


Servers
This script restarts the “Spooler” service on
multiple servers.
$Servers = @("Server1", "Server2")

foreach ($Server in $Servers) {


Restart-Service -InputObject (Get-Service
-ComputerName $Server -Name "Spooler")
Write-Host "Restarted Spooler on $Server"
}

15. Test Internet Connectivity


Test-NetConnection -ComputerName google.com -Port 443
16. Check Windows Update Status
Get-WindowsUpdateLog

17. Get the Last Boot Time of a Server


(Get-CimInstance Win32_OperatingSystem).LastBootUpTime

18. Install Active Directory Role


Install-WindowsFeature -Name AD-Domain-Services
-IncludeManagementTools
Write-Host "Installed AD DS Role"

19. Promote a Server to a Domain


Controller
Install-ADDSForest -DomainName "domain.com" -InstallDNS

20. Generate a System Health Report


perfmon /report

Conclusion

These scripts automate key tasks in Active


Directory and Windows Server management,
making administration easier and more efficient.
Would you like scheduled automation for some
of these tasks?

Scheduled Automation for Active


Directory & Windows Server Tasks

You can automate these PowerShell scripts using


Task Scheduler in Windows Server. Below are
steps and scripts for scheduled automation of
key tasks.
1. Schedule a Task Using Task
Scheduler (Manual Steps)
1. Open Task Scheduler (taskschd.msc).
2. Click Create Basic Task.
3. Enter a Name & Description.
4. Select Trigger (e.g., Daily, Weekly, or At
Startup).
5. Choose Action: Start a Program.
6. In Program/script, enter:
powershell.exe

7. In Add arguments, enter:


-File "C:\Scripts\YourScript.ps1"

8. Click Finish.
2. Automate Bulk User Creation
(Weekly)
This script creates users from a CSV file every
Monday at 8 AM.

PowerShell Script: CreateUsers.ps1


Import-Module ActiveDirectory
$users = Import-Csv "C:\Scripts\users.csv"

foreach ($user in $users) {


$SecurePassword = ConvertTo-SecureString
$user.Password -AsPlainText -Force
New-ADUser -GivenName $user.FirstName -Surname
$user.LastName -SamAccountName $user.UserName `
-UserPrincipalName "$
($user.UserName)@domain.com" -Path $user.OU
-AccountPassword $SecurePassword `
-Enabled $true
Write-Host "Created User: $($user.UserName)"
}

Schedule Task
• Trigger: Weekly (Monday at 8:00 AM)
• Action: Run "C:\Scripts\CreateUsers.ps1"
3. Disable Inactive Users (Monthly)
This script disables AD accounts that haven’t
logged in for 90+ days.

PowerShell Script:
DisableInactiveUsers.ps1
$DaysInactive = 90
$Date = (Get-Date).AddDays(-$DaysInactive)

$Users = Get-ADUser -Filter {LastLogonDate -lt $Date


-and Enabled -eq $true} -Properties LastLogonDate

foreach ($User in $Users) {


Disable-ADAccount -Identity $User.SamAccountName
Write-Host "Disabled: $($User.SamAccountName)"
}

Schedule Task
• Trigger: Monthly (1st of each month at 12:00
AM)
• Action: Run "C:
\Scripts\DisableInactiveUsers.ps1"
4. Backup Group Policy Objects
(Daily)
This script backs up all GPOs to a folder every
night at 2 AM.

PowerShell Script: BackupGPOs.ps1


$BackupPath = "C:\GPOBackups\$(Get-Date -Format yyyy-
MM-dd)"
New-Item -ItemType Directory -Path $BackupPath -Force
Backup-GPO -All -Path $BackupPath
Write-Host "GPO Backup Completed: $BackupPath"

Schedule Task
• Trigger: Daily (2:00 AM)
• Action: Run "C:\Scripts\BackupGPOs.ps1"
5. Export AD Users and Groups
(Weekly)
This script exports all users & groups to a CSV
file.

PowerShell Script: ExportADData.ps1


$Date = Get-Date -Format "yyyy-MM-dd"
$Users = Get-ADUser -Filter * -Property MemberOf |
Select-Object SamAccountName, DisplayName, MemberOf
$Users | Export-Csv "C:\Reports\AD_Users_$Date.csv"
-NoTypeInformation
Write-Host "Exported AD users to C:
\Reports\AD_Users_$Date.csv"
Schedule Task
• Trigger: Weekly (Sunday at 10:00 PM)
• Action: Run "C:\Scripts\ExportADData.ps1"
6. Restart Domain Controllers
(Monthly)
This script reboots all Domain Controllers every
first Sunday of the month at 3 AM.

PowerShell Script: RestartDCs.ps1


$DCs = Get-ADDomainController -Filter *
foreach ($DC in $DCs) {
Restart-Computer -ComputerName $DC.HostName -Force
Write-Host "Restarted: $($DC.HostName)"
}

Schedule Task
• Trigger: Monthly (First Sunday at 3:00 AM)
• Action: Run "C:\Scripts\RestartDCs.ps1"
7. Check for Locked Users (Hourly)
This script logs locked-out users every hour.
PowerShell Script:
CheckLockedUsers.ps1
$LockedUsers = Get-ADUser -Filter {LockedOut -eq $true}
if ($LockedUsers) {
$LockedUsers | Out-File "C:\Logs\LockedUsers.log"
-Append
Write-Host "Logged locked-out users."
}

Schedule Task
• Trigger: Every hour
• Action: Run "C:
\Scripts\CheckLockedUsers.ps1"
8. Restart Print Spooler Service (Every
Night)
This script restarts the Print Spooler service
every night at 1 AM.

PowerShell Script: RestartSpooler.ps1


Restart-Service -Name "Spooler"
Write-Host "Print Spooler Restarted"

Schedule Task
• Trigger: Daily (1:00 AM)
• Action: Run "C:\Scripts\RestartSpooler.ps1"
9. Test Internet Connection (Every 5
Minutes)
This script checks internet connectivity every 5
minutes.

PowerShell Script: CheckInternet.ps1


$Test = Test-NetConnection -ComputerName google.com
-Port 443
if ($Test.TcpTestSucceeded -eq $false) {
"Internet Down: $(Get-Date)" | Out-File "C:
\Logs\InternetStatus.log" -Append
}

Schedule Task
• Trigger: Every 5 minutes
• Action: Run "C:\Scripts\CheckInternet.ps1"
10. Cleanup Old Log Files (Daily)
This script deletes log files older than 30 days.

PowerShell Script: CleanupLogs.ps1


$Path = "C:\Logs"
$Days = 30
$Now = Get-Date
Get-ChildItem -Path $Path -Recurse | Where-Object
{ $_.LastWriteTime -lt $Now.AddDays(-$Days) } | Remove-
Item -Force
Write-Host "Old logs deleted from $Path"

Schedule Task
• Trigger: Daily (4:00 AM)
• Action: Run "C:\Scripts\CleanupLogs.ps1"
Conclusion

By using Task Scheduler, these PowerShell


scripts will run automatically, ensuring efficient
Active Directory and Windows Server
management.

Would you like email alerts for these tasks?

Email Alerts for Automated AD &


Windows Server Tasks

You can configure PowerShell scripts to send


email alerts whenever a scheduled task runs. This
guide includes:
1. SMTP Configuration for sending emails.
2. Modifying Scripts to Include Email
Alerts.
3. Example: Sending Email When a Task
Completes.
4. Example: Alert When Locked-Out
Users are Found.
5. Example: Alert When Internet
Connection Fails.
1. Configure SMTP for Sending Emails
PowerShell Send-MailMessage allows sending
emails via SMTP.

SMTP Settings Example (Office 365)

Modify this part according to your mail server.


$SMTPServer = "smtp.office365.com"
$SMTPPort = "587"
$From = "[email protected]"
$To = "[email protected]"
$Username = "[email protected]"
$Password = ConvertTo-SecureString "YourPassword"
-AsPlainText -Force
$Credential = New-Object
System.Management.Automation.PSCredential ($Username,
$Password)
For Gmail, use:
• $SMTPServer = "smtp.gmail.com"
• $SMTPPort = "587"
• Enable “Less Secure Apps” or use an App
Password.
2. Modify Scripts to Include Email
Alerts

Example 1: Email Alert When User


Cleanup Completes

Sends an email when inactive users are disabled.


$DaysInactive = 90
$Date = (Get-Date).AddDays(-$DaysInactive)
$Users = Get-ADUser -Filter {LastLogonDate -lt $Date
-and Enabled -eq $true} -Properties LastLogonDate

$DisabledUsers = @()
foreach ($User in $Users) {
Disable-ADAccount -Identity $User.SamAccountName
$DisabledUsers += $User.SamAccountName
}

# Email Notification
$Subject = "Inactive Users Disabled"
$Body = "The following users were disabled due to
inactivity:`n" + ($DisabledUsers -join "`n")
Send-MailMessage -To $To -From $From -Subject $Subject
-Body $Body -SmtpServer $SMTPServer -Credential
$Credential -UseSsl -Port $SMTPPort
Write-Host "Email Sent!"

Example 2: Alert for Locked-Out Users

Sends an email when locked-out users are found.


$LockedUsers = Get-ADUser -Filter {LockedOut -eq $true}

if ($LockedUsers) {
$Body = "The following accounts are locked:`n" +
($LockedUsers.SamAccountName -join "`n")
$Subject = "ALERT: Locked-Out Users Detected"

Send-MailMessage -To $To -From $From -Subject


$Subject -Body $Body -SmtpServer $SMTPServer
-Credential $Credential -UseSsl -Port $SMTPPort
Write-Host "Email Sent for Locked-Out Users!"
}

Example 3: Alert When Internet Fails

Sends an immediate alert when the server loses


internet connectivity.
$Test = Test-NetConnection -ComputerName google.com
-Port 443
if ($Test.TcpTestSucceeded -eq $false) {
$Body = "The server lost internet connectivity at $
(Get-Date)"
$Subject = "ALERT: Server Lost Internet Connection"
Send-MailMessage -To $To -From $From -Subject
$Subject -Body $Body -SmtpServer $SMTPServer
-Credential $Credential -UseSsl -Port $SMTPPort
Write-Host "Internet Failure Alert Sent!"
}

Example 4: Alert When a Domain


Controller Restarts

This script sends an email notification when a


Domain Controller reboots.
$DCs = Get-ADDomainController -Filter *
$RebootedDCs = @()

foreach ($DC in $DCs) {


Restart-Computer -ComputerName $DC.HostName -Force
$RebootedDCs += $DC.HostName
}

# Send Email Notification


$Body = "The following Domain Controllers were
restarted:`n" + ($RebootedDCs -join "`n")
$Subject = "ALERT: Domain Controllers Restarted"

Send-MailMessage -To $To -From $From -Subject $Subject


-Body $Body -SmtpServer $SMTPServer -Credential
$Credential -UseSsl -Port $SMTPPort
Write-Host "Reboot Alert Sent!"

Example 5: Send a Daily AD Report


This script generates a daily AD user report and
emails it.
$Date = Get-Date -Format "yyyy-MM-dd"
$ReportFile = "C:\Reports\AD_Users_$Date.csv"

# Export AD Users
$Users = Get-ADUser -Filter * -Property SamAccountName,
DisplayName, Enabled, LastLogonDate
$Users | Export-Csv $ReportFile -NoTypeInformation

# Send Email with Report Attachment


$Subject = "Daily AD User Report - $Date"
$Body = "Please find the attached Active Directory User
Report."
Send-MailMessage -To $To -From $From -Subject $Subject
-Body $Body -Attachments $ReportFile -SmtpServer
$SMTPServer -Credential $Credential -UseSsl -Port
$SMTPPort

Write-Host "AD Report Sent!"

3. Schedule These Scripts in Task


Scheduler
Each script can be scheduled as a Task Scheduler
Job:
1. Open Task Scheduler (taskschd.msc).
2. Click Create Basic Task.
3. Set the Trigger (Daily, Weekly, or
Custom).
4. Set Action → Start a Program → Enter:
powershell.exe -ExecutionPolicy Bypass -File "C:
\Scripts\YourScript.ps1"

5. Click Finish.
4. Bonus: Send Email Alerts Without
Hardcoding Passwords
For security, instead of storing plaintext
passwords in scripts, use Secure Credentials
Storage.

Step 1: Save Credentials Securely

Run this once manually:


$Credential = Get-Credential
$Credential | Export-Clixml -Path "C:
\Scripts\SMTP_Creds.xml"

Step 2: Use Stored Credentials in Scripts

Modify scripts to import credentials securely:


$Credential = Import-Clixml -Path "C:
\Scripts\SMTP_Creds.xml"
Send-MailMessage -To $To -From $From -Subject "Test
Email" -Body "Test" -SmtpServer $SMTPServer -Credential
$Credential -UseSsl -Port $SMTPPort

Final Thoughts

Now, email alerts will notify IT admins of


important events:
• User actions (creation, disabling).
• Locked-out accounts.
• Internet failures.
• Domain Controller reboots.
• Daily AD Reports.

Would you like a centralized logging solution for


all these alerts?

Centralized Logging & Monitoring for


AD & Windows Server Automation

To keep track of all automation events and alerts,


we’ll set up a centralized logging system that
stores logs in a shared log file and optionally
sends email alerts for critical events.
1. Centralized Log File for All Scripts
Create a Log File (C:
\Logs\AutomationLog.log)

Modify all your PowerShell scripts to log events


into this centralized log file.

Logging Function

Place this function in every script:


Function Write-Log {
param (
[string]$Message,
[string]$Level = "INFO"
)
$LogFile = "C:\Logs\AutomationLog.log"
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
"$Timestamp [$Level] $Message" | Out-File -Append
-FilePath $LogFile
}

Now, every script can call Write-Log "Your


message" to log events.
2. Modify Scripts to Use Centralized
Logging
Example: Logging User Cleanup
Import-Module ActiveDirectory

Write-Log "Starting inactive user cleanup..."

$DaysInactive = 90
$Date = (Get-Date).AddDays(-$DaysInactive)
$Users = Get-ADUser -Filter {LastLogonDate -lt $Date
-and Enabled -eq $true} -Properties LastLogonDate

foreach ($User in $Users) {


Disable-ADAccount -Identity $User.SamAccountName
Write-Log "Disabled inactive user: $
($User.SamAccountName)"
}

Write-Log "Inactive user cleanup completed."

3. Send Email Alerts for Critical Logs

Function to Send Email for Errors


Function Send-AlertEmail {
param (
[string]$Subject,
[string]$Body
)

$SMTPServer = "smtp.office365.com"
$SMTPPort = "587"
$From = "[email protected]"
$To = "[email protected]"
$Credential = Import-Clixml -Path "C:
\Scripts\SMTP_Creds.xml"
Send-MailMessage -To $To -From $From -Subject
$Subject -Body $Body -SmtpServer $SMTPServer
-Credential $Credential -UseSsl -Port $SMTPPort
}

Function Write-Log {
param (
[string]$Message,
[string]$Level = "INFO"
)
$LogFile = "C:\Logs\AutomationLog.log"
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
"$Timestamp [$Level] $Message" | Out-File -Append
-FilePath $LogFile

# Send Email for Critical Errors


if ($Level -eq "ERROR") {
Send-AlertEmail -Subject "Critical Alert:
Automation Failure" -Body "$Timestamp - $Message"
}
}

Now, Use the Enhanced Write-Log in Any


Script
Write-Log "Starting scheduled task: Internet Check"

$Test = Test-NetConnection -ComputerName google.com


-Port 443
if ($Test.TcpTestSucceeded -eq $false) {
Write-Log "Server lost internet connectivity!"
-Level "ERROR"
}

Write-Log "Internet check completed."


🔹 If ERROR is logged, it will send an email
alert automatically.
4. Daily Log Summary Email
This script sends a daily summary of logs.
$LogFile = "C:\Logs\AutomationLog.log"
$LogContent = Get-Content $LogFile | Out-String

$Subject = "Daily Automation Log Summary"


$Body = "Here is the daily log summary:`n`n$LogContent"

Send-AlertEmail -Subject $Subject -Body $Body


Write-Host "Daily log summary sent!"

Schedule This to Run Daily


• Trigger: Every day at 7 AM
• Action: Run "C:
\Scripts\SendDailyLogEmail.ps1"
5. Export Logs to CSV for Tracking
To make logs analyzable, store them in CSV
format:
$LogFile = "C:\Logs\AutomationLog.csv"
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"

$LogEntry = [PSCustomObject]@{
Timestamp = $Timestamp
Event = "Scheduled Task Executed"
Status = "Success"
}

$LogEntry | Export-Csv -Path $LogFile -Append


-NoTypeInformation

This lets you filter logs by date/status in Excel.


6. Bonus: View Logs in PowerShell

Last 50 Log Entries


Get-Content "C:\Logs\AutomationLog.log" -Tail 50

Filter Logs for Errors


Select-String -Path "C:\Logs\AutomationLog.log"
-Pattern "ERROR"

Final Overview

✅ Centralized Logging: All scripts log to C:


\Logs\AutomationLog.log.
✅ Email Alerts for Critical Failures: Errors
trigger email alerts automatically.
✅ Daily Summary Reports: A daily email
summarizes all automation tasks.
✅ CSV Export for Analysis: Logs can be
viewed in Excel.
✅ Easy Log Viewing: PowerShell can filter logs
quickly.

Would you like integration with SIEM tools


(Splunk, ELK, etc.) for advanced monitoring?

Advanced Monitoring & SIEM


Integration for Active Directory &
Windows Server Logs

To enhance security, visibility, and analytics, we


will integrate Active Directory and Windows
Server logs into SIEM (Security Information
and Event Management) tools like Splunk,
ELK (Elasticsearch, Logstash, Kibana), or
Azure Sentinel.
1. SIEM Options & Log Integration
Methods
SIEM Tool Integration Method
Splunk Forward logs via Splunk Universal Forwarder or
REST API
ELK Stack (Elasticsearch, Logstash, Kibana) Use
Winlogbeat (Elastic Agent) or Logstash for AD & PowerShell
logs
Azure Sentinel Connect via Log Analytics Agent (Azure
Monitor)
Graylog Forward logs using NXLog or Winlogbeat

2. Send Logs to Splunk


Splunk can collect logs from Active Directory,
PowerShell, and Windows Server Events.

Step 1: Install Splunk Universal


Forwarder
1. Download & Install Splunk Forwarder
on the Windows Server.
• Download Splunk Forwarder
2. Configure Forwarding to Splunk
Server:
.\splunk add forward-server splunkserver:9997 -auth
admin:changeme

3. Enable Windows Event Logs &


PowerShell Logging:
.\splunk enable boot-start
.\splunk add monitor "C:\Logs\AutomationLog.log"

Step 2: Verify Logs in Splunk


1. Log into Splunk Web (http://
splunkserver:8000).
2. Run the search query:
index=windows source="C:\Logs\AutomationLog.log"

3. Set up Dashboards & Alerts.


3. Send Logs to ELK Stack
(Elasticsearch, Logstash, Kibana)

Step 1: Install & Configure Winlogbeat


1. Download & Install Winlogbeat from
Elastic:
• Download Winlogbeat
2. Edit winlogbeat.yml Configuration:
winlogbeat.event_logs:
- name: Security
- name: System
- name: Application
output.elasticsearch:
hosts: ["http://elasticsearch:9200"]
index: "winlogbeat-%{[agent.version]}-%{+yyyy.MM.dd}"

3. Start the Winlogbeat Service:


Start-Service winlogbeat

Step 2: Configure Logstash to Parse AD


& PowerShell Logs
1. Edit Logstash config (logstash.conf):
input {
beats {
port => 5044
}
}
filter {
grok {
match => { "message" => "%
{TIMESTAMP_ISO8601:timestamp} \[%{WORD:level}\] %
{GREEDYDATA:message}" }
}
}
output {
elasticsearch {
hosts => ["http://elasticsearch:9200"]
index => "windows-logs"
}
}
2. Start Logstash:
logstash -f logstash.conf

Step 3: View Logs in Kibana


1. Open Kibana Web UI (http://
kibana:5601).
2. Go to “Discover” → Index windows-
logs.
3. Set up visualizations & alerts.
4. Send Logs to Azure Sentinel
Azure Sentinel is a cloud-native SIEM that
integrates with Azure Active Directory &
Windows Server logs.

Step 1: Connect Windows Server to Azure


Sentinel
1. Install Log Analytics Agent on the server:
.\AzureMonitorAgent.msi /q /l*v loginstall.txt
2. Configure Data Collection Rules in
Azure Portal:
• Enable Security Logs
• Enable PowerShell Logs (Microsoft-
Windows-PowerShell/Operational)

Step 2: Send PowerShell Logs to Sentinel


1. Open Group Policy Editor (gpedit.msc).
2. Go to Computer Configuration →
Administrative Templates → Windows
Components → PowerShell.
3. Enable:
• Turn on Module Logging
• Turn on Script Block Logging

Step 3: Query Logs in Sentinel

Use Kusto Query Language (KQL) to search


logs:
SecurityEvent
| where EventID == 4688
| where ProcessName contains "powershell"

5. Send Logs to Graylog


Step 1: Install & Configure NXLog
1. Install NXLog for Windows.
2. Edit C:\Program Files
(x86)\nxlog\conf\nxlog.conf:
<Input in>
Module im_file
File "C:\Logs\AutomationLog.log"
SavePos TRUE
ReadFromLast TRUE
</Input>

<Output out>
Module om_udp
Host graylog-server
Port 514
</Output>

<Route 1>
Path in => out
</Route>

3. Restart NXLog:
Restart-Service nxlog

Step 2: View Logs in Graylog


1. Open Graylog Web UI (http://
graylog:9000).
2. Search for logs:
source:windows-server

6. Set Up Real-Time Alerts in SIEM


Each SIEM tool allows alerting based on log
events.

Splunk Alert for Failed Logins


1. Open Splunk Web → Search:
index=windows EventCode=4625

2. Click Save as Alert → Set Trigger


Conditions.

ELK Alert for AD User Lockouts


1. Open Kibana → Stack Management →
Alerts.
2. Create an alert for:
event.code: 4740
Azure Sentinel Alert for PowerShell
Attacks
1. Open Sentinel → Analytics → New Rule.
2. Add KQL Query:
SecurityEvent
| where EventID == 4104
| where EventData contains "Invoke-Mimikatz"

Final Overview
SIEM Tool Integration Method
Splunk Splunk Forwarder + REST API
ELK Stack Winlogbeat + Logstash
Azure Sentinel Log Analytics Agent + KQL Queries
Graylog NXLog Forwarding

✅ All automation logs are now stored centrally.


✅ Real-time alerts notify IT teams about
security issues.
✅ SIEM dashboards visualize AD, PowerShell,
and Server events.

Would you like a pre-configured dashboard


template for Splunk or Kibana?
Pre-Configured SIEM Dashboards for
Splunk & Kibana

Below are ready-to-use dashboard templates for


Splunk and Kibana (ELK Stack) to monitor
Active Directory, Windows Server, and
PowerShell automation logs.
1. Splunk Dashboard for Active
Directory & Server Monitoring

Steps to Import Splunk Dashboard


1. Log into Splunk Web (http://
splunkserver:8000).
2. Click Dashboards → Create New
Dashboard.
3. Enter Dashboard Title (e.g., “AD &
Server Monitoring”).
4. Click Source (Switch to XML Mode).
5. Paste the XML Code below.
6. Click Save & View Dashboard.

Splunk Dashboard XML


<dashboard>
<label>Active Directory & Server Monitoring</label>
<row>
<panel>
<title>Locked-Out Users</title>
<chart>
<search>
<query>index=windows EventCode=4740
| stats count by User</query>
</search>
<option name="chart">pie</option>
</chart>
</panel>
<panel>
<title>Failed Logins (Event ID 4625)</
title>
<chart>
<search>
<query>index=windows EventCode=4625
| timechart count by User</query>
</search>
<option name="chart">line</option>
</chart>
</panel>
</row>
<row>
<panel>
<title>Server Reboots</title>
<chart>
<search>
<query>index=windows EventCode=6005
OR EventCode=6006 | timechart count</query>
</search>
<option name="chart">bar</option>
</chart>
</panel>
<panel>
<title>PowerShell Script Execution</title>
<chart>
<search>
<query>index=windows source="C:
\Logs\AutomationLog.log" | stats count by Level</query>
</search>
<option name="chart">column</option>
</chart>
</panel>
</row>
</dashboard>

✅ This Splunk Dashboard visualizes:


• Locked-out users (Event ID 4740).
• Failed login attempts (Event ID 4625).
• Server reboots & shutdowns (Event IDs
6005 & 6006).
• PowerShell script execution logs.
2. Kibana (ELK Stack) Dashboard for
AD & Server Logs

Steps to Import Kibana Dashboard


1. Log into Kibana (http://kibana:5601).
2. Go to Stack Management → Saved
Objects.
3. Click Import → Select the JSON file
below.
4. Go to Dashboard → Open the new
dashboard.
Kibana Dashboard JSON

Save this JSON file as


Kibana_AD_Dashboard.json and import it.
{
"type": "dashboard",
"attributes": {
"title": "Active Directory & Server
Monitoring",
"panelsJSON": "[{\"type\":\"visualization\",
\"id\":\"locked-out-users\",\"gridData\":
{\"x\":0,\"y\":0,\"w\":6,\"h\":3},\"panelIndex\":\"1\",
\"embeddableConfig\":{}}]",
"version": 1
}
}

Kibana Visualizations Setup


1. Go to Visualizations → Create New
Visualization.
2. Select “Data Table” and configure:
• Index: winlogbeat-*
• Query:
event.code: 4740

• Metrics: Count (User).


3. Save it as “Locked-Out Users”.
4. Create another bar chart visualization:
• Index: winlogbeat-*
• Query:
event.code: 4625

• Metrics: Count by Time.


• Save it as “Failed Logins”.
3. Real-Time Alerts for Security
Threats

Splunk Alert: Detecting Brute-Force


Attacks
1. Go to Search.
2. Run:
index=windows EventCode=4625 | stats count by User |
where count > 10

3. Click Save As → Alert.


4. Configure:
• Trigger Condition: count > 10 failed
logins.
• Action: Send Email to Admin.

Kibana Alert: Multiple Failed Logins


1. Go to “Stack Management” → “Alerts”.
2. Create a rule with:
• Query:
event.code: 4625 AND event.action: "failed login"

• Trigger Condition: >10 attempts in 5


minutes.
• Action: Send email alert.
4. Additional Dashboards & Metrics
Metric Splunk Query Kibana Query
Locked-Out Users `index=windows EventCode=4740stats
count by User`
PowerShell Execution index=windows source="C:
\Logs\AutomationLog.log" event.code: 4104
Server Reboots `index=windows EventCode=6005 OR
EventCode=6006 timechart count`
Active Directory User Creation index=windows
EventCode=4720 event.code: 4720
Unusual Admin Activity `index=windows EventCode=4672
stats count by User`

Final Overview

✅ Splunk & Kibana Dashboards visualize AD


& Windows Server logs.
✅ Real-time Alerts for security threats (Brute-
force, PowerShell attacks).
✅ Easy Import of Dashboards (XML for
Splunk, JSON for Kibana).
✅ Automatic Email Alerts for critical events.

Would you like pre-configured JSON/XML files


for direct import?

You might also like