0

We have 3 terminal servers and end up having to kick off a user daily. I am totally new to PS and learning what I can, but having problems here with this.

The script prompts for the username, then searches the 3 servers to find which one they're on and gives me their Session ID. I then have to input the server # and Session ID and run the Invoke-RDUserLogoff command, but the problem is, I need to run that command as my domain admin account... my standard user account does not have permissions to do this.

Maybe there's even a completely different/better way to do this?

Thanks in advance.

$user = read-host -prompt "What is the USERNAME you need to disconnect?"

$term1 = qwinsta /server:ts1 | findstr "$user"
$term2 = qwinsta /server:ts2 | findstr "$user"
$term3 = qwinsta /server:ts3 | findstr "$user"

write-host TS1
$term1

write-host TS2
$term2

write-host TS3
$term3

$term = read-host -prompt "Which terminal server is the user on? (1, 2, or 3?)"
$id = read-host -prompt "To logoff the user, enter their ID #:"

Invoke-RDUserLogoff -HostServer ts$term -UnifiedSessionID $id -Force 

1 Answers1

0

Below is a quick and simple way of capturing a server match. It will return a false positive though if you search for a user 'a.paris' and there's a 'a.paris2' user logged on. The $tsId capture will fail if there are multiple matches.

$user = Read-Host -prompt "What is the USERNAME you need to disconnect?"
'ts1','ts2','ts3' | ForEach-Object {
  $server = $_
  $result = qwinsta /server:$server | Where-Object { $_ -match $user }
  if($result) {
    $tsId = ($result.Trim() -replace '\s+',',').Split(',')[1]
    Invoke-RDUserLogoff -HostServer $server -UnifiedSessionID $tsId -Force 
  }
}

The $tsId line trims the result line, replaces whitespace with commas. The Id is the 2nd element of the array (PowerShell arrays are zero-based - hence the 1.

EDIT 1: If all you're after is a GUI to kick off a user, then try this: http://www.lazywinadmin.com/p/lazyts.html

EDIT 2: If you want to run as a different user, see two answers for ideas: SF; SO.

Or, alternatively (and a bit simpler), you could shift+right-click on the PowerShell/ISE Start Menu item, then choose 'Run as different user'.

Community
  • 1
  • 1
TechSpud
  • 3,418
  • 1
  • 27
  • 35
  • Thanks, I'll look this over and experiment and try to learn what's going on since I want to force myself to learn PS anyway. But I think again, my normal account doesn't have permission to RDUserLogoff on a TS, so is there a way to run that Invoke command with a different account that does have permission? – A Paris Feb 16 '17 at 18:15
  • I'd stick with simple solutions for now - if all you want to do is kick a user off a TS session, try the lazyts. `Invoke-RDUserLogOff` doesn't have a `-Credential` param, so you'd have to run a script block, job, or PS session as the other user. I'll add a couple of links to my answer to give you a few ideas. – TechSpud Feb 17 '17 at 07:57