# Set the number of days of inactivity before a user is removed $inactiveDays = 30 # Set the path to the directory where the user folders are stored $userFolderPath = "C:\Users" # Get the current date $currentDate = Get-Date # Create an array to store the users that will be removed $usersToRemove = @() # Loop through each user folder in the user folder path and its subdirectories Get-ChildItem -Path $userFolderPath -Recurse -Directory | ForEach-Object { $userFolder = $_ # Check if the folder being checked is a user folder $userAccount = Get-LocalUser -Name $userFolder.Name -ErrorAction SilentlyContinue if ($userAccount -ne $null) { # Get the last modified date of the user folder $lastModifiedDate = $userFolder.LastWriteTime # Calculate the number of days since the user folder was last modified $daysSinceModified = ($currentDate - $lastModifiedDate).Days # If the number of days since the user folder was last modified is greater than or equal to the inactive days limit, add the user to the array of users to remove if ($daysSinceModified -ge $inactiveDays) { $usersToRemove += $userAccount } } } # Check if there are any users to remove if ($usersToRemove.Count -gt 0) { # Create a selectable list of the users to be removed $selectedUsers = $usersToRemove | Out-GridView -Title "Select users to remove" -PassThru if ($selectedUsers.Count -gt 0) { # Create a confirmation prompt to display the list of selected users to be removed $promptMessage = "The following users will be removed:`n`n" + ($selectedUsers | Select-Object -ExpandProperty Name -Join "`n") $confirm = Read-Host -Prompt $promptMessage -Default "N" # If the user confirms the removal, loop through the array of users to remove and delete them if ($confirm -eq "Y" -or $confirm -eq "y") { foreach ($user in $selectedUsers) { Write-Host "Removing user $($user.Name) due to inactivity" # Check if the "Remove-LocalUser" cmdlet is available before attempting to use it if (Get-Command -Name "Remove-LocalUser" -ErrorAction SilentlyContinue) { Remove-LocalUser -Name $user.Name -Confirm:$false # Log which users were removed and when Add-Content -Path "C:\UserRemovalLog.txt" -Value "$($user.Name) was removed on $(Get-Date)" } else { Write-Host "Remove-LocalUser cmdlet not available. User $($user.Name) not removed." # Log that the Remove-LocalUser cmdlet was not available Add-Content -Path "C:\UserRemovalLog.txt" -Value "Remove-LocalUser cmdlet not available. User $($user.Name) not removed on $(Get-Date)" } } } else { Write-Host "User removal canceled." } } else { Write-Host "No users selected for removal." } } else { Write-Host "No inactive users found." }