Public/Invoke-UserLogoff.ps1
<#
.SYNOPSIS Log off user sessions on specified remote computers. .DESCRIPTION This function allows you to log off user sessions on specified remote computers. You can specify the target computer names for which you want to log off user sessions. .PARAMETER ComputerName Specifies the name(s) of the remote computer(s) from which you want to log off user sessions. If not provided, defaults to the local computer. .EXAMPLE Invoke-UserLogoff -ComputerName "RemoteComputer1", "RemoteComputer2" This example logs off all user sessions on the specified remote computers. .NOTES Requires PowerShell remoting and appropriate administrative credentials. #> function Invoke-UserLogoff { [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [Alias("CN")] [string[]]$ComputerName = $env:COMPUTERNAME ) begin { $ErrorActionPreference = 'Stop' } process { foreach ($Computer in $ComputerName) { try { if (Test-Connection -ComputerName $Computer -Count 2 -Quiet) { $OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer -ErrorAction Stop $ComputerSystem = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $Computer -ErrorAction Stop if (($OS.Caption -like '*Windows 10*' -or $OS.Caption -like '*Windows 11*') -and (-not $ComputerSystem.DomainRole -or $ComputerSystem.DomainRole -eq 1)) { if ($User = $ComputerSystem.UserName) { Write-Output "Computer in use by $User." Write-Output 'Logging off user sessions...' $sessionID = ((qwinsta /server:$Computer| ForEach-Object { (($_.trim() -replace “\s+”,”,”))} | ConvertFrom-Csv) | Where-Object "SessionName" -EQ "console").ID $result = logoff $sessionID /server:$Computer if ($result -eq 'ERROR') { Write-Output "Session $sessionID on $Computer got stuck and couldn't be logged off." } } else { Write-Output 'Not logged on.' } } else { Write-Output "Computer $Computer is a server or not running Windows 10/11. Skipping logoff process." } } else { Write-Output 'Computer offline.' } } catch { Write-Error $_.Exception.Message } } } } |