fbpx
Active Directory & Office 365 Reporting Tool

Active Directory Security Automation with PowerShell. PowerShell offers a vast collection of built-in commands-cmdlets to facilitate the management of system components. With its integration into the .NET Framework, PowerShell allows accessing to a wide range of functionalities, and and it interacts with various Windows components and services. It’s integration with various Microsoft products and services, such as Active Directory (AD), enhances its utility in managing computing environments.

Administrators use PowerShell scripts to automate a range of tasks related to Active Directory, including the cyber security. Also used for auditing purposes and in pair with Windows Server Task Scheduler, PowerShell scripts are used for retrieving detailed reports that help administrators understand the security situation better. In addition to the preventive measures, scripts are also used to swiftly respond to and mitigate security incidents, helping to automate the urgent tasks that would have take days to be performed manually.

Continue with Active Directory Security Automation with PowerShell to find out what is next. 

Using PowerShell for Active Directory Auditing

All Windows Server machines, including Active Directory Domain Controllers, have built-in event logging for auditing purpose. Event Logs contain system logs, applications logs, services logs, etc. Monitoring of Security log records is considered one of the cybersecurity auditing good practices. Notifications about the log records are configured using the third-party monitoring systems, but if no such system is in place alerting for the Event Logs is configured using PowerShell scripts. For example by setting email alerts with Send-MailMessage cmdlet. Using Event Viewer, you create a task that sends an alert each time a certain event is recorded.

As an example, we create a task that sends an email each time a security group is changed.

  1. Create a PowerShell script that sends a simple email notification to the IT administrator and save it as PS1 file.
    1. In case the email server you use for SMTP relay requires authentication (the recommended way), you need to prepare the credentials you use. Create a service account in AD (in our example it is domain\report-service) and save its password hash in the text file using the ConvertTo-SecureString cmdlet:
				
					ConvertTo-SecureString "P@ssW0rD!" -AsPlainText -Force | Out-File "C:\Secrets\report-pwd.txt"
				
			

Ensure that you run the command using the same account that will be used to run the task, because hash can be decrypted only using the same account on the same computer where it was encrypted.

 

    1. Create the script:
				
					$User = "domain\report-service"
$Password = Get-Content "C:\Secrets\report-pwd.txt" | ConvertTo-SecureString 
$Credentials = New-Object System.Management.Automation.PSCredential ($User, $Password)
Send-MailMessage -To administrator@domain.local  -From report-service@domain.local `
-Subject "Event was recorded" -Body “Event ID 4755 was recorded in the security log” `
-SmtpServer EmailServer.domain.local -Credential $Credentials -Port 587

				
			

In the above script, SmtpServer and Port parameters are used to specify the email server that processes the message sending and the TCP port used. The detailed description of the parameters of the Send-MailMessage cmdlet are here.

  1. Each time the property or membership of a group is altered, Event ID 4755 is recorded in the Security logs. Go to Event Viewer, find such event, right click on it and select Attach Task to This Event.
  1. Create Basic Task Wizard appears. Enter the name for the task, optionally add the description and press Next.
  1. Leave the next page as is and press Next again.
  1. On the Action step, select the option Start a program and press Next again.
  1. On the next step, in the section Program/script enter powershell.exe, it  instructs the task which program to use. In the Add arguments section, specify the full path to the PS1 file of the script you want to be triggered in case of event. Press Next and then Finish.

Similarly, create different tasks to be triggered by event logs to automate the auditing. The list of events to monitor are found in the Events to Monitor article.

Try our Active Directory & Office 365 Reporting & Auditing Tools

Try us out for Free.  100’s of reports available to gain control of your IAM.

Improve your AD & Entra ID security & compliance.

Reporting Automation Using PowerShell

Another useful way to use PowerShell to automate security related tasks is to create scheduled reports. For example, the reports are used to get information about non-complaint objects in the Active Directory. Let’s create a script that reports the list of AD user accounts which have passwords set to never expire.

				
					$Date = get-date -UFormat %Y-%m-%d
$OutputFile = "C:\Reports\PWDNeverExpire-$Date.xls"
"Name" + "`t" + "UserPrincipalName" | Out-File $OutputFile -Force
 $NonCompliantUsers = Get-ADUser -filter * -properties Name, PasswordNeverExpires |`
 where { $_.passwordNeverExpires -eq "true" } | where {$_.enabled -eq "true"}                    
ForEach ($NCUser in $NonCompliantUsers)
    {  $NCUser.Name + "`t" +  $NCUser.UserPrincipalName | Out-File $OutputFile -Append }
   
$User = "domain\report-service"
$Password = Get-Content "C:\Secrets\report-pwd.txt" | ConvertTo-SecureString 
$Credentials = New-Object System.Management.Automation.PSCredential ($User, $Password)
Send-MailMessage -To administrator@domain.local  -From report-service@domain.local`
-Subject "Accounts with password set to never expire" -SmtpServer EmailServer.domain.local `
-Credential $Credentials -Port 587 -Attachments $OutputFile

				
			

The script creates the XLS file (table that uses tab symbol as a separator), then parses the Active Directory to find the accounts with passwordNeverExpires attribute set to True. Then PowerShell writes the found accounts to the file and sends it via email to the administrator. The script should run periodically (usually daily), and the schedule is configured using Task Scheduler. To do it, follow the below steps:

  1. In the Server Manager, go to Tools > Task Scheduler.
  1. In the appeared window, right click on Task Scheduler Library and select Create Basic Task.
  1. In the Create Basic Task Wizard, enter the name for the task, optionally add the description and press Next.
  1. On the Trigger page, select Daily and press Next.
  1. On the next page, configure the schedule and press Next.
  1. On the Action step, select the option Start a program and select Next.
  1. On the Start a Program step, in the section Program/script enter exe, and in the Add arguments section, specify the full path to the PS1 file of the script. Press Next and then Finish.

Responding to Security Incidents

As it was mentioned earlier, PowerShell is a powerful automation tool that makes the management of Windows System easier. And in addition to it, using PowerShell for Active Directory domain-joined machines offers several advantages over managing standalone machines, primarily due to the centralized management capabilities and automation potential that Active Directory (AD) integration provides. When machines are part of an AD domain, administrators leverage PowerShell to execute scripts and commands across multiple machines simultaneously, streamlining administrative tasks and ensuring uniformity in settings and policies across the network. Life-saving in cases where a security incident has already occurred and you need to respond to it as quickly as possible.

For example a security incident , where one of the external DNS servers is compromised (rerouting the network traffic or phishing). First, identify the scope of the problem and collect the list of the machines that use this DNS server for name resolution. Use a PowerShell script for this purpose:

				
					$Computers=Get-ADComputer -Filter *
 ForEach ($Computer in $Computers)
{$Result=Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled = 'True'"`
 -Property DNSServerSearchOrder -ComputerName $Computer.DNSHostname 
$output = new-object PSObject 
$output | add-member NoteProperty "ComputerName" $Computer.DNSHostname
$output | add-member NoteProperty "DNSServerSearchOrder" $Result.DNSServerSearchOrder
$output}

				
			

Another example – you suspect a malicious activity in the network, and assume that some virus changes the local Administrator accounts on the domain-joined computers. To identify on which computers the local account was recently changed, you may look for the Event ID 4738 on the Security log. You may query all computers in the network for this event using simple PowerShell script:

				
					$Computers=Get-ADComputer -Filter *
 ForEach ($Computer in $Computers)
{Get-WinEvent -ComputerName $Computer.DNSHostname -FilterHashtable @{
    LogName = 'Security'
    ID = 4740} |  ?{$_.message -like "*administrator*"}
}
				
			

That is it from us. Article Active Directory Security Automation with PowerShell is summarized below.

Active Directory Security Automation with PowerShell Conclusion

This article has shown how PowerShell can turn the time-consuming and often error-filled work of managing network security into a more streamlined and reliable process. By using scripts to keep an eye on security, create reports, and deal with security issues, IT administrators protect their systems more effectively.

PowerShell helps with everything from keeping track of what’s happening in the Active Directory environment to quickly sending out alerts if something seems off. The given example serves as a starting point for admins to build their own automated systems, customized for their specific needs. Reporting, an essential part of keeping a network safe, has been made easier with PowerShell, allowing for the automatic creation and sharing of reports that highlight potential security risks. When it comes to responding to security problems, the speed and flexibility offered by PowerShell are invaluable. Being able to quickly figure out a problem and fix it across the entire network is crucial.

To sum it up, bringing PowerShell into the mix for managing Active Directory’s security can make a big difference in fighting off cyber threats. Automating security tasks not only makes the job of IT personnel easier and more accurate but also helps organizations react faster to threats. As we look ahead, it’s clear that using PowerShell in smart and creative ways will be key to building stronger, more secure infrastructure.

InfraSOS-AD-Tools

Try InfraSOS for FREE

Try InfraSOS Active Directory, Azure AD & Office 365 Reporting & Auditing Tool

Marat M

Marat M

System administrator with 14 years of practical experience. Specializes in Microsoft products such as Exchange Server, Active Directory, Microsoft 365 and Azure.

Leave a comment

Your email address will not be published. Required fields are marked *