Techibee.com

Powershell: How to logoff remote computer

In my one of my recent posts, I talked about shutdown the remote computer using Powershell. Since then I started exploring the other options available in Win32_OperatingSystem class and figured out one more helpful method which can logoff users logged on remote computers.

This script helps you to logoff the remote user who is current loogged on the computer. I didn’t test this against terminal services environment where multiple users are logged in, but you can try this and let me know how it goes.

Code:

[cmdletbinding()]            
            
param (            
            
 [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]            
 [string[]]$ComputerName = $env:computername,            
 [switch]$Force            
             
)            
            
begin {            
 $Username = $env:username            
             
 if($force) { $flag = 4 } else { $flag = 0 }             
 $comment  = "Logoff initiated by $Username using $($MyInvocation.InvocationName). Timeout is $Timeout"            
}            
            
process {            
 foreach($Computer in $ComputerName) {            
              
  Write-Verbose "Working on $Computer"            
  if(Test-Connection -ComputerName $Computer -Count 1 -ea 0) {            
   $OS  = Get-WMIObject -Class Win32_OperatingSystem -ComputerName $Computer            
   if( -not $OS.Win32ShutdownTracker(0, $comment, 0, $flag)) {            
    $Status  = "FAILED"            
   } else {            
    $Status  = "SUCCESS"            
   }            
  $OutputObj = New-Object -TypeName PSobject             
  $OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer            
  $OutputObj | Add-Member -MemberType NoteProperty -Name LogOffStatus -Value $status            
  $OutputObj | Add-Member -MemberType NoteProperty -Name Timeout -Value $timeout            
  $OutputObj            
  }            
 }            
}            
            
end {            
}

Usage:

.\Logoff-Computer.ps1 -ComputerName MyPC1

Exit mobile version