Powershell找出断开的RDP会话并同时注销 [英] Powershell to find out disconnected RDP session and log off at the same time

查看:332
本文介绍了Powershell找出断开的RDP会话并同时注销的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在可以从任何服务器注销断开连接的RDP会话的脚本?这造成了很多麻烦,并且广告帐户不断遭到锁定.

Is there a script that can log out my disconnected RDP session from any server? This is causing a lot of pain and constant ad account lockouts.

任何帮助都会很棒.

推荐答案

我已经找到答案了,我正在写这个答案来帮助需要帮助的人,因为我必须自己弄清楚这个问题.我使用在线资源创建了一个脚本,以找出AD环境中所有Windows Server上断开连接的RDP会话.我在每个Windows Server上运行一个查询,并创建一个CSV格式的列表,然后使用该列表从这些服务器中注销我的ID,因此我没有任何断开的会话.

I have got the answer and I am writing this answer to help someone in need as I had to figure this out myself. I created a script using online resources to find out disconnected RDP sessions on all Windows Server in my AD environment. I run a query on each Windows Server and create a CSV formatted list, I then use that list to log out my ID from those servers, so I don't have any disconnected sessions.

我这样做是为了确保我的AD帐户在更改密码时不会因为某些RDP会话断开而被锁定.

I did this to make sure my AD account doesn't get locked out due to some disconnected RDP sessions when its time to change my password.

您可以根据需要随意修改此脚本.

You are free to modify this script as per your need.

脚本代码如下:

param (
        #get current logged on username
        [string]$UserName = $env:USERNAME
    )

    # Import the Active Directory module for the Get-ADComputer CmdLet
    Import-Module ActiveDirectory


    # Query Active Directory for enabled windows servers computer accounts and sort by name
    $Servers = Get-ADComputer -Filter {(OperatingSystem -like "*windows*server*") -and (Enabled -eq "True")} | Sort Name

    # Initiating variables
    $SessionList = $NULL
    $queryResults = $NULL
    $SError = $null
    $SDown = $null
    $z = 0

    # Get total number of servers
    $count = $Servers.count 


    # Start looping through each server at a time
    ForEach ($Server in $Servers) {    

        # initiate counter for showing progress
        $z = $z + 1

        $ServerName = $Server.Name

        # Start writing progress 
        Write-Progress -Activity "Processing Server: $z out of $count servers." -Status " Progress" -PercentComplete ($z/$Servers.count*100)

        # check if server is pingable before running the query on the server
        if (Test-Connection $Server.Name -Count 1 -Quiet) {  

            Write-Host "`n`n$ServerName is online!" -BackgroundColor Green -ForegroundColor Black

            Write-Host ("`nQuerying Server: `"$ServerName`" for disconnected sessions under UserName: `"" + $UserName.ToUpper() + "`"...") -BackgroundColor Gray -ForegroundColor Black

            # Store results in array
            [array]$queryResults += (

                # Query server for specific username
                query user $UserName /server:$ServerName | 
                foreach {
                    # Look for lines with Disc string to filter out active sessions
                    if ($_ -match "Disc") {

                        # format the output in CSV by replacing more than 2 spaces with a comman
                        write-output ("`n$ServerName," + (($_.trim() -replace ' {2,}', ',')))
                    }
                }
            )
        }
        # If server is not pingable show error message
        else {
            # Make list of server that are down.
            [array]$SDown += ($ServerName)
            Write-Host "`nError: Unable to connect to $ServerName!" -BackgroundColor red -ForegroundColor white
            Write-Host "Either the $ServerName is down or check for firewall settings on server $ServerName!" -BackgroundColor Yellow -ForegroundColor black
        }
    }

    # If there are some non pingable server then display the list
    if ($SDown -ne $null -and $SDown) {
            Write-Host "`nScript was unable to connect to the following server:" -ForegroundColor White -BackgroundColor Red
            $SDown
    }

    # Check if any disconnected session are stored in the array
    if ($queryResults -ne $null -and $queryResults) {

        # Convert the CSV fromat to table format with headers
        $QueryResultsCSV = $queryResults | ConvertFrom-Csv -Delimiter "," -Header "ServerName","UserName","SessionID","CurrentState","IdealTime","LogonTime"

        # Show the results on console
        $QueryResultsCSV |ft -AutoSize

        # Go through each Disconnected session stored in the array
        $QueryResultsCSV | foreach {

            # Grabb session ID and ServerName
            $Sessionl = $_.SessionID
            $Serverl = $_.ServerName

            # Show message on the console
            Write-Host "`nLogging off"$_.username"from $serverl..." -ForegroundColor black -BackgroundColor Gray
            sleep 2

            # Logout user using session ID
            logoff $Sessionl /server:$Serverl /v

        }
    }
    else {
        # if array is empty display message that no session were found
        Write-Host `n`n`n`n("*" * $LineSize)
        Write-Host "You are all good! No ghost sessions found!" -BackgroundColor Green -ForegroundColor Black
        Write-Host ("*" * $LineSize)
    }

    # Pause at the end so you can capture the output
    $null = Read-Host "`n`nScript execution finished, press enter to exit!"

屏幕截图:

  1. 当脚本在所有服务器上运行时,向您显示联机和脱机服务器:

  1. When the script is running on through all server, shows you online and offline servers:

脚本无法连接的服务器列表:

List of servers that Script was unable to connect:

该脚本列出了发现断开连接的RDP会话的服务器.

The script lists the servers where it found disconnected RDP sessions.

当脚本开始注销断开连接的会话时,它会在结尾处暂停.

When script start to log your disconnected sessions off and it pauses at the end.

这篇关于Powershell找出断开的RDP会话并同时注销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆