powershell script to kill .exe terminal server disconnected session

1k Views Asked by At

I'm looking for a method to kill a .exe of disconnected terminal session. It's about Navision; We have limited licences and want to keep killing the ones that aren't in use.

I know there are methods to completely logoff the disconnected session, but I prefer to only close this specific progress.

I did find a blogpost with a code that is discribed to do exactly what i'm looking for. A powershell script that's sheduled to scan for a certain .exe on disconnected sessions, and kill it off. http://www.interworks.com/blogs/jpoehls/2012/12/12/killing-processes-disconnected-terminal-service-sessions the code is posted on this webpage.

Unfortunately it doesn't work, I get the following error:

PS C:\scripts> .\navscript.ps1
An empty pipe element is not allowed.
At C:\scripts\navscript.ps1:91 char:10
+         | <<<<  % { $id = $_;
+ CategoryInfo          : ParserError: (:) [
+ FullyQualifiedErrorId : EmptyPipeElement

Besides alot of time spent on google to find different solutions, I also tried to remove the empty line at line 90. this resulted in another error:

PS C:\scripts> .\navscript.ps1
Exception calling "Substring" with "2" argument(s): "Lengte kan niet minder dan nul zijn.
Parameternaam: length"
At C:\scripts\navscript.ps1:52 char:44
+                     ;"ID" = $line.Substring <<<< ($line.IndexOf(" ",     $starters.Username), $starters.ID - $line.IndexO
f(" ", $starters.Username) + 2).trim()
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException

I hope someone has an idea how to get this working.

1

There are 1 best solutions below

0
On

The query session command output is localized, therefore its substrings in Get-Sessions that are hardcoded into the function are unable to get triggered if the very first line does not match the expected line of:

 SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE

Note that there's a space at the first symbol of the line.

So, to fix the script, you have to run query session on the target PC, get the first line and manually update lines 40 through 45 with correct character sequences displayed in the first line of localized output.