Site Tools


log_off_a_user_from_a_remote_computer

Hier ein Script um einen Useraccount von einem PC abzumelden ohne RDP oder dergleichen benutzen zu müssen. Einfach nur noch den Accountnamen und den Computernamen eintragen und los geht´s. Es beinhaltet schon einen Teil um einen Fehler zu beheben der immer wieder mal auftreten kann.

logofsingleuserfromsinglepcremote.ps1
<
Write-Host 
Write-Host "Log off single User from single PC remotely" -foreground "yellow"
Write-Host
 
function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}
$ScriptPath = Get-ScriptDirectory
 
function Get-LoggedInUser
{
    [CmdletBinding()]
    param
    (
        [ValidateNotNullOrEmpty()]
        [String[]]$ComputerName = $env:COMPUTERNAME
    )
 
    $out = @()
 
    ForEach ($computer in $ComputerName)
    {
        try { if (-not (Test-Connection -ComputerName $computer -Quiet -Count 1 -ErrorAction Stop)) { Write-Warning "Can't connect to $computer"; continue } }
        catch { Write-Warning "Can't test connect to $computer"; continue }
 
        $quserOut = quser.exe /SERVER:$computer 2>&1
        if ($quserOut -match "No user exists")
        { Write-Warning "No users logged in to $computer";  continue }
 
		#$users[$i].logonTime = [datetime]::ParseExact($users[$i].logonTime, "dd/MM/yyyy HH:mm", $null)
 
        $users = $quserOut -replace '\s{2,}', ',' |
        ConvertFrom-CSV -Header 'username', 'sessionname', 'id', 'state', 'idleTime', 'logonTime' |
        Add-Member -MemberType NoteProperty -Name ComputerName -Value $computer -PassThru
 
        $users = $users[1..$users.count]
 
        for ($i = 0; $i -lt $users.count; $i++)
        {
            if ($users[$i].sessionname -match '^\d+$')
            {
                $users[$i].logonTime = $users[$i].idleTime
                $users[$i].logonTime = [datetime]::ParseExact($users[$i].logonTime, "dd/MM/yyyy HH:mm", $null)
                $users[$i].STATE = $users[$i].ID
                $users[$i].ID = $users[$i].SESSIONNAME
                $users[$i].SESSIONNAME = $null
            }
 
            # cast the correct datatypes
            $users[$i].ID = [int]$users[$i].ID
 
            $idleString = $users[$i].idleTime
            if ($idleString -eq '.') { $users[$i].idleTime = 0 }
 
            # if it's just a number by itself, insert a '0:' in front of it. Otherwise [timespan] cast will interpret the value as days rather than minutes
            if ($idleString -match '^\d+$')
            { $users[$i].idleTime = "0:$($users[$i].idleTime)" }
 
            # if it has a '+', change the '+' to a colon and add ':0' to the end
            if ($idleString -match "\+")
            {
                $newIdleString = $idleString -replace "\+", ":"
                $newIdleString = $newIdleString + ':0'
                $users[$i].idleTime = $newIdleString
            }
 
            $users[$i].logonTime = [datetime]::ParseExact($users[$i].logonTime, "dd/MM/yyyy HH:mm", $null)
            $users[$i].logonTime = [datetime]$users[$i].logonTime
        }
        $users = $users | Sort-Object -Property idleTime
        $out += $users
    }
    Write-Output $out
}
 
$cmdlet = "ActiveDirectory" 
if ( (get-command -Name $cmdlet -ErrorAction SilentlyContinue) -eq $null ) {Import-module ActiveDirectory} 
 
$ExecUser = ([Environment]::UserName) 
 
$ServerName = Read-Host "please enter ServerName"
$UserID = Read-Host "please enter UserID to Logoff"
 
$qusererror = query user /server:$ServerName
 
if ($qusererror -contains '0x00000005')
{
Invoke-Command -ComputerName $ServerName -ScriptBlock {
$registryPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server'
$Name = "AllowRemoteRPC"
$value = "1"
New-ItemProperty -Path $registryPath -Name $name -Value $value -PropertyType DWORD -Force }}
 
$IDValue = Get-LoggedInUser -ComputerName $ServerName | where { $_.username -eq $UserID } | select-object -ExpandProperty id
$IDValue
 
if ($IDValue -ne $Null)
{
Write-Host "Do you really like to logoff User?" -foreground "yellow"
Write-Host 
Write-Host "1.  Logoff" -foreground "yellow"
Write-Host "2.  Stop and Quit" -foreground "yellow"
Write-host						
 
$auswahl = read-host -Prompt 'Please choose'
 
Write-Host 
 
if ($auswahl -eq 1) {
Write-Host "User $UserID with Session $IDValue will be logged off from Server $ServerName now" -foreground "yellow"
logoff $IDValue /server:$ServerName
Write-Host "User $UserID with Session $IDValue is logged off from Server $ServerName" -foreground "yellow"}
else {Write-Host "***** Stopped! Try again or do it manually. *****" -foreground "yellow"
Break
}}
 
else {Write-Host "User $UserID is not logged on to Server $ServerName" -foreground "yellow"}
log_off_a_user_from_a_remote_computer.txt · Last modified: 2018/10/17 22:41 by 212.204.110.133