<# Use this script to scan the SQL error log for failed logins and automatically add them to the Windows firewall. #> #Use REGEX to create the patternfor IP addresses $ipPattern = [Regex]::new("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}") #Create a variable to hold the IP addresses that we DO NOT want added to the firewall rule $own_IPs = [Regex]::new("(127\.0\.0\.1|198\.23\.255\.226|198\.23\.255\.227|198\.23\.255\.228|198\.23\.255\.229|73\.117\.147\.[0-9]{1,3})") #Search the SQL error log for entries with an IP address (IP's are logged when there is a login failure) $result = gc "C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\Log\ERRORLOG" | Select-String ${ipPattern} | Select-String -notmatch $own_IPs #Output all of the IP's found to a text file $result.Matches.value | Out-File ips.txt #Open the output text file, sort the list and get rid of duplicate IP's, saving the file list to a new file Get-Content ips.txt | Sort-Object | Get-Unique -AsString | Out-File unique_ips.txt #Loop through the list of unique IP's and update the firewall rulle $ips = @() foreach ($ip in Get-Content unique_ips.txt) { Try { if ((Get-NetFirewallRule -DisplayName "IP Block SQL Server" | Get-NetFirewallAddressFilter).RemoteAddress -eq $ip) { # debug: # Write-Host "IP ${ip} already blocked" continue } else { $ips += $ip } } Catch { } Finally { } } if($ips.length -gt 0) { Set-NetFirewallRule -DisplayName "IP Block SQL Server" -RemoteAddress $ips }