AD Scripts
Jump to navigation
Jump to search
Remove Sessions by User
# Define the username to log out and domain (adjust these values accordingly) $userToLogoff = "username" $domain = "DOMAIN" # Ensure the Active Directory module is loaded Import-Module ActiveDirectory # Get all computer objects from Active Directory $hosts = Get-ADComputer -Filter * | Select-Object -ExpandProperty Name # Loop through each host foreach ($host in $hosts) { # Use Invoke-Command to run commands remotely on each host Invoke-Command -ComputerName $host -ScriptBlock { # Find the session ID of the user's session using quser $sessions = quser /server:$using:host | Where-Object { $_ -match $using:userToLogoff } foreach ($session in $sessions) { # Extract the session ID $sessionId = ($session -split '\s+')[2] if ($sessionId -ne "SESSIONNAME") { # Log off the session logoff $sessionId /server:$using:host Write-Output "Logged off $($using:userToLogoff) from session $sessionId on $using:host" } } } -Credential "$domain\$userToLogoff" -ErrorAction SilentlyContinue }
Find Processes by User
# Define the username to log out and domain (adjust these values accordingly) $userToLogoff = "username" $domain = "DOMAIN" # Ensure the Active Directory module is loaded Import-Module ActiveDirectory # Get all computer objects from Active Directory $hosts = Get-ADComputer -Filter * | Select-Object -ExpandProperty Name # Loop through each host foreach ($host in $hosts) { # Use Invoke-Command to run commands remotely on each host Invoke-Command -ComputerName $host -ScriptBlock { # Find the session ID of the user's session using quser $sessions = quser /server:$using:host | Where-Object { $_ -match $using:userToLogoff } foreach ($session in $sessions) { # Extract the session ID $sessionId = ($session -split '\s+')[2] if ($sessionId -ne "SESSIONNAME") { # Log off the session logoff $sessionId /server:$using:host Write-Output "Logged off $($using:userToLogoff) from session $sessionId on $using:host" } } } -Credential "$domain\$userToLogoff" -ErrorAction SilentlyContinue }