Skip to content

Instantly share code, notes, and snippets.

@mortenya
mortenya / Remove-OldIISLogs.ps1
Last active September 26, 2024 15:14
Script to run as a Scheduled Task to clean out IIS logs older than 30 days.
<#
Shamelessly liberated from http://foxdeploy.com/2015/02/11/automatically-delete-old-iis-logs-w-powershell/
Because it was better than my own.
#>
$LogPath = "C:\inetpub\logs"
$maxDaystoKeep = -30
$outputPath = "c:\CleanupTask\Cleanup_Old_logs.log"
$itemsToDelete = dir $LogPath -Recurse -File *.log | Where LastWriteTime -lt ((get-date).AddDays($maxDaystoKeep))
@mortenya
mortenya / Send-AccountLockoutEmail.ps1
Created April 17, 2015 21:10
I created this script to send a notification email about account lockouts. Just run as a Scheduled Task on all AD DCs.
<#
For use in a scheduled task on an Active Directory Domain Controller
Name: Lockout Email
Trigger: On event - Log: Security, Source: Microsoft-Windows-Security-Auditing, Event ID: 4740
#>
$AccountLockOutEvent = Get-EventLog -LogName "Security" -InstanceID 4740 -Newest 1
$LockedAccount = $($AccountLockOutEvent.ReplacementStrings[0])
$AccountLockedAt = $($AccountLockOutEvent.ReplacementStrings[1])
$AccountLockOutEventTime = $AccountLockOutEvent.TimeGenerated
@mortenya
mortenya / Manage-EventLogArchives.ps1
Last active August 29, 2015 14:17
I wanted to keep a log of all fileshare access, at the file access level, so I enabled 'Detailed File Share - Success' logging. 2 of my fileshares generate minimal logs, 1-2GB per day, but 1 of them is generating about 20GB or more (we need to evaluate usage...) so I'm running this script to trigger off Event ID 1105 (the Event Log has been arch…
# Function to zip the archived log, requires 7zip (has command line version)
function Create-7zip([String] $sourceDir, [String] $zipFileName)
{
[string]$pathToZipExe = "C:\scripts\7zip\7za.exe";
[Array]$arguments = "a", "-tzip", "$zipFileName", "$sourceDir", "-r";
& $pathToZipExe $arguments;
}
# get the event that containts the filename for the archived security log
# for v3.0+ Get-WinEvent -LogName Security -MaxEvents 1 -Oldest
@mortenya
mortenya / Get-DisabledInheritanceUsers.ps1
Last active August 29, 2015 14:16
Had a number of users in my environment that had AdminCount=1 and Security Inheritance disabled, AdminCount was easy, enabling inheritance required a bit more work. This is so I don't forget how I did it. Seems to take a few minutes to replicate up where ADUC will see the changes.
## list of users, I wanted to control exactly what got modified.
## this command will get all the users we want to work with:
### Get-ADUser -Filter * -Properties nTSecurityDescriptor | `
### where { $_.nTSecurityDescriptor.AreAccessRulesProtected -eq $true } | `
### select Name,SamAccountName,DistinguishedName,nTSecurityDescriptor
$users = Import-Csv C:\scripts\users.csv
## allows inheritance
[bool]$isProtected = $false
## preserves inherited rules
[bool]$PreserveInheritance = $true
@mortenya
mortenya / Backup-SecurityEventLog.ps1
Last active August 29, 2015 14:16
From a few examples on StackOverflow I put together this POC script for backing up and zipping Windows Security Logs to save them for compliance
# Function to zip the archived log, requires .NET 4.5
function zipFiles($sourceDir, $zipFileName)
{
Add-Type -Assembly System.IO.Compression.FileSystem
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
[System.IO.Compression.ZipFile]::CreateFromDirectory($sourceDir, $zipFileName, $compressionLevel, $false)
}
# Function to zip the archived log, requires 7zip (has command line version)
function create-7zip([String] $sourceDir, [String] $zipFileName)
@mortenya
mortenya / Generate-RandomPassword.ps1
Last active August 29, 2015 14:15
Incomplete, but the point is to change the local admin password on all computers, would then need to drop that password and $env:COMPUTERNAME into an encrypted spreadsheet so that you could get it.
$Computers = Get-ADComputer -Filter * | Where distinguishedName -NotLike "*DC*"
$user = Get-WmiObject Win32_UserAccount -Filter "LocalAccount=true" | where { $_.Name -eq 'Administrator' }
$Count = 1
$CharSet1 = [Char[]]"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
ForEach ($c in $Computers)
{ Write-Progress -Id 1 -Activity "Changing Server Passwords" -Status "Current Progress: $Count of $($Servers.Count): $($Server.Name)" -PercentComplete (($Count / $c.Count) * 100)
$Ping = Test-Connection $c.Name -Count 2 -Quiet
If ($Ping) {
$Password = (($CharSet1 | Get-Random -Count 5) -join "") + " " + `
@mortenya
mortenya / New-DSSearcher.ps1
Created February 6, 2015 21:49
A very simple Directory Searcher example.
$strFilter = "(&(objectClass=Person)(objectCategory=User))"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "Subtree"
@mortenya
mortenya / Get-LoggedOnUserSession.ps1
Last active October 14, 2015 21:25
A function that grabs all logon sessions from the script center
function Get-LoggedOnUserSession {
#mjolinor 3/17/10
[CmdletBinding()]
param
(
[Parameter(Position=0,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[string[]]$Name = $env:COMPUTERNAME)
@mortenya
mortenya / Get-MemberOf.ps1
Last active August 29, 2015 14:12
Just one way to get the names, (CN), of the groups that an ADUser is a member of.
(Get-ADUser –Identity $user –Properties MemberOf).MemberOf -replace '^CN=([^,]+),OU=.+$','$1' > c:\user-groups.txt
# The -replace will strip the CN of the group from the Distinguished Name.
# This isn't error proof, but will be adequate for most use cases when dealing with Security Groups.
@mortenya
mortenya / Get-DefinitionUpdates.ps1
Last active August 29, 2015 14:12
Function to grab Definition updates for Windows Defender. Felt a little messy how I used the foreach loop, but it works.
Function WSUSUpdate {
<#
Slight modification of https://gist.github.com/jacobludriks/9ca9ce61de251a5476f1
#>
$Criteria = "IsInstalled=0 and Type='Software'"
$Searcher = New-Object -ComObject Microsoft.Update.Searcher
try {
$SearchResult = $Searcher.Search($Criteria).Updates
if ($SearchResult.Count -eq 0) {
Write-Output "There are no applicable updates."