Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

remote desktop - qwinsta /server:somesrv equivalent in Powershell?

When I run the qwinsta /server:somesrv command in cmd I can get a listing of all the current RDP sessions that are logged into a particular Windows server.

 SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
 console                                     0  Conn    wdcon
 rdp-tcp                                 65536  Listen  rdpwd
 rdp-tcp#594       tom1                      1  Active  rdpwd
 rdp-tcp#595       bob1                      2  Active  rdpwd

Is it possible to get a list like this on a remote server from Powershell so that the data can be used elsewhere?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are multiple alternatives:

  • Use the Terminal Services PowerShell Module. Easy solution.
  • Writing a powershell wrapper that parses the output of qwinsta to objects. Easy solution. See example below
  • Use the Cassia.DLL .Net wrapper to access the native APIs that qwinsta runs behind the scene. This is the class that the TS Module uses. More difficult, but will have the benefit of being customized to your needs.
  • Go crazy and use the Native Methods that Cassia.DLL accesses using P/Invoke (wtsapi32.dll, kernel32.dll, winsta.dll). Hard and overcomplicated.

PowerShell-wrapper for qwinsta

function Get-TSSessions {
    param(
        $ComputerName = "localhost"
    )

    qwinsta /server:$ComputerName |
    #Parse output
    ForEach-Object {
        $_.Trim() -replace "s+",","
    } |
    #Convert to objects
    ConvertFrom-Csv
}

Get-TSSessions -ComputerName "localhost" | ft -AutoSize

SESSIONNAME USERNAME ID     STATE  TYPE DEVICE
----------- -------- --     -----  ---- ------
services    0        Disc                     
console     Frode    1      Active            
rdp-tcp     65537    Listen     

#This is objects, so we can manipulate the results to get the info we want. Active sessions only:
Get-TSSessions -ComputerName "localhost" | ? { $_.State -eq 'Active' } | ft -AutoSize SessionName, UserName, ID

SESSIONNAME USERNAME ID
----------- -------- --
console     Frode    1 

          

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...