powershell script om .exe te killen terminal server

Pagina: 1
Acties:
  • 427 views

Acties:
  • 0 Henk 'm!

  • Narkimo
  • Registratie: Februari 2015
  • Laatst online: 29-09 20:18
Hallo, Ik ben op zoek naar een methode om een .exe te killen van disconnected terminal sessies. Het gaat hier om Navision, in verband met Licenties. Mensen klikken op het kruisje in plaats van hun sessie af te melden, dus blijft dit proces draaien. Nu zijn er methodes om disconnected sessies af te melden, maar het liefst wil ik alleen navision afsluiten.

Nu heb ik een blogpost gevonden met precies de situatie omschreven zoals ik hem nodig heb. Een powershell script dat gesheduled is, om om de zoveel tijd te scannen voor disconnected sessies met dat proces open. http://www.interworks.com...terminal-service-sessions

Helaas werkt het niet. Ik krijg de volgende foutmelding.
code:
1
2
3
4
5
6
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

Nou heb ik wat gegoogled wat pipe elements zijn en heb hier wat basis dingen over gelezen, ook heb ik de foutmelding gegoogled en wat dingen geprobeerd zoals te regel af te sluiten met een ` etc.Dit resulteerd in weer nieuwe errors. :) Aangezien ik totaal niet thuis ben in de powershell scripts lijkt dit onbegonnen werk. Daarom hoop ik dat iemand hier ziet wat er aan de hand is en hoe dit op te lossen is.

Acties:
  • 0 Henk 'm!

  • Icekiller2k6
  • Registratie: Februari 2005
  • Laatst online: 12:33
Kun je misschien ook je code delen?

edit:
kun je even code tags gebruiken?
code:
1
[ code ] zonder spaties [ / code ]

[ Voor 60% gewijzigd door Icekiller2k6 op 16-06-2015 16:23 ]

MT Venus E 5KW (V151) P1 HomeWizard | Hackerspace Brixel te Hasselt (BE) - http://www.brixel.be | 9800X3D, 96GB DDR5 6000MHZ, NVIDIA GEFORCE 4090, ASRock X670E Steel Legend, Seasonic GX1000


Acties:
  • 0 Henk 'm!

  • Narkimo
  • Registratie: Februari 2015
  • Laatst online: 29-09 20:18
Icekiller2k6 schreef op dinsdag 16 juni 2015 @ 16:20:
Kun je misschien ook je code delen?
Hoi, die staat in het linkje, handig met regelnummers en kleurcodes. Maar hier is ie ook als externe sites een probleem zijn.
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
    # This script supports being run with -WhatIf and -Confirm parameters.
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium')]
    param (
        # Regex of the states that should be included in the process killing field.
        [string]$IncludeStates = '^(Disc)$', # Only DISCONNECTED sessions by default.
        # Regex of the processes to kill
        [string]$KillProcesses = '^(OUTLOOK)$', # Only OUTLOOK by default.
        [int]$GracefulTimeout = 15 # Number of seconds to wait for a graceful shutdown before forcefully closing the program.
    )
     
    function Get-Sessions
    {
        # `query session` is the same as `qwinsta`
     
        # `query session`: http://technet.microsoft.com/en-us/library/cc785434(v=ws.10).aspx
     
        # Possible session states:
        <#
        [URL="http://support.microsoft.com/kb/186592"]Terminal Server Commands: QUERY[/URL]
        Active. The session is connected and active.
        Conn.   The session is connected. No user is logged on.
        ConnQ.  The session is in the process of connecting. If this state
                continues, it indicates a problem with the connection.
        Shadow. The session is shadowing another session.
        Listen. The session is ready to accept a client connection.
        Disc.   The session is disconnected.
        Idle.   The session is initialized.
        Down.   The session is down, indicating the session failed to initialize correctly.
        Init.   The session is initializing.
        #>
     
        # Snippet from http://poshcode.org/3062
        # Parses the output of `qwinsta` into PowerShell objects.
        $c = query session 2>&1 | where {$_.gettype().equals([string]) }
     
        $starters = New-Object psobject -Property @{"SessionName" = 0; "Username" = 0; "ID" = 0; "State" = 0; "Type" = 0; "Device" = 0;};
         
        foreach($line in $c) {
             try {
                 if($line.trim().substring(0, $line.trim().indexof(" ")) -eq "SESSIONNAME") {
                    $starters.Username = $line.indexof("USERNAME");
                    $starters.ID = $line.indexof("ID");
                    $starters.State = $line.indexof("STATE");
                    $starters.Type = $line.indexof("TYPE");
                    $starters.Device = $line.indexof("DEVICE");
                    continue;
                }
               
                New-Object psobject -Property @{
                    "SessionName" = $line.trim().substring(0, $line.trim().indexof(" ")).trim(">")
                    ;"Username" = $line.Substring($starters.Username, $line.IndexOf(" ", $starters.Username) - $starters.Username)
                    ;"ID" = $line.Substring($line.IndexOf(" ", $starters.Username), $starters.ID - $line.IndexOf(" ", $starters.Username) + 2).trim()
                    ;"State" = $line.Substring($starters.State, $line.IndexOf(" ", $starters.State)-$starters.State).trim()
                    ;"Type" = $line.Substring($starters.Type, $starters.Device - $starters.Type).trim()
                    ;"Device" = $line.Substring($starters.Device).trim()
                }
            } catch {
                throw $_;
                #$e = $_;
                #Write-Error -Exception $e.Exception -Message $e.PSMessageDetails;
            }
        }
    }
     
    # Helper function for getting the singular or plural form of
    # a word based on the given count.
    # Because we want proper log messages.
    function Get-ProperWord([string]$singularWord, [int]$count) {
        if ($count -eq 0 -or $count -gt 1) {
            if ($singularWord.EndsWith("s")) {
                return "$($singularWord)es";
            }
            else {
                return "$($singularWord)s";
            }
        }
        else {
            return $singularWord;
        }
    }
     
    # Get a list of all terminal sessions that are in the state we care about.
    $IncludedSessions = Get-Sessions `
                            | Where { $_.State -match $IncludeStates } `
                            | Select -ExpandProperty ID
     
    # Get a list of all processes in one of those terminal sessions
    # that match a process we want to kill.
    $SessionProcesses = $IncludedSessions `
     
        | % { $id = $_;
              Get-Process `
                | Where { $_.SessionID -eq $id -and $_.Name -match $KillProcesses } }
     
    # Get some words to use in log output.
    $wordSecond = $(Get-ProperWord 'second' $GracefulTimeout)
    $wordProcess = $(Get-ProperWord 'process' $SessionProcesses.Length)
     
    if ($SessionProcesses.Length -gt 0) {
        # Initiate a graceful shutdown of the processes.
        # http://powershell.com/cs/blogs/tips/archive/2010/05/27/stopping-programs-gracefully.aspx
        Write-Output "Gracefully closing $($SessionProcesses.Length) $wordProcess"
        $SessionProcesses `
            | % { if ($PSCmdlet.ShouldProcess("$($_.Name) ($($_.Id))", "CloseMainWindow")) { $_.CloseMainWindow() } } `
            | Out-Null
     
        # Wait X seconds for the programs to close gracefully.
        Write-Output "Waiting $GracefulTimeout $wordSecond for the $wordProcess to close"
        if ($GracefulTimeout -gt 0) {
            if ($PSCmdlet.ShouldProcess("Current Process", "Start-Sleep")) {
                Start-Sleep -Seconds $GracefulTimeout
            }
        }
     
        # Force any remaining processes to close, the hard way.
        Write-Output "Forcefully closing any remaining processes"
        $SessionProcesses `
            | Where { $_.HasExited -ne $true } `
            | Stop-Process -ErrorAction SilentlyContinue
    }
    else {
        Write-Output "No processes to close"
    }

Acties:
  • 0 Henk 'm!

  • Swedish Clown
  • Registratie: November 2010
  • Laatst online: 10-04 22:41

Swedish Clown

Erlang <3

Ik heb zo'n vemoeden dat die lege regel op line 90 de boel breekt. Regel 89 bevat namelijk een continuation quote `, maar vervolgens is regel 90 leeg. Wat ervoor zorgt dat er inderdaad niks gepiped wordt in regel 91.

Haal die lege regel op regel 90 maar eens weg.

(Disclaimer: Het is een behoorlijke tijd geleden dat ik in PoSh heb geschreven.

Dat terzijde, de foutmelding is aardig specifiek ;)
An empty pipe element is not allowed.
At C:\scripts\navscript.ps1:91 char:10

Always looking for developers wanting to work with Erlang.


Acties:
  • 0 Henk 'm!

  • Narkimo
  • Registratie: Februari 2015
  • Laatst online: 29-09 20:18
Brakkie41 schreef op dinsdag 16 juni 2015 @ 16:39:
Ik heb zo'n vemoeden dat die lege regel op line 90 de boel breekt. Regel 89 bevat namelijk een continuation quote `, maar vervolgens is regel 90 leeg. Wat ervoor zorgt dat er inderdaad niks gepiped wordt in regel 91.

Haal die lege regel op regel 90 maar eens weg.

(Disclaimer: Het is een behoorlijke tijd geleden dat ik in PoSh heb geschreven.

Dat terzijde, de foutmelding is aardig specifiek ;)
An empty pipe element is not allowed.
At C:\scripts\navscript.ps1:91 char:10
Bedankt voor je suggestie, ik heb het geprobeerd, maar hij komt dan met een andere foutmelding op de proppen. Ik weet niet of het een gevolg van het verwijderen van de lege regel is, of dat er meerdere fouten in het script zitten.

code:
1
2
3
4
5
6
7
8
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

Acties:
  • 0 Henk 'm!

  • FastPinguin
  • Registratie: Oktober 2009
  • Laatst online: 05-09 15:15
Ik doe maar een gok. Ik zie door heel de code een punt met iets erachter, misschien kan je hiermee experimenteren:
| % { $id = $_.iets;

Acties:
  • 0 Henk 'm!

  • Narkimo
  • Registratie: Februari 2015
  • Laatst online: 29-09 20:18
FastPinguin schreef op dinsdag 16 juni 2015 @ 16:59:
Ik doe maar een gok. Ik zie door heel de code een punt met iets erachter, misschien kan je hiermee experimenteren:
| % { $id = $_.iets;
Bedankt, wat ik er ook neerzet, hij blijft met dezelfde foutmelding komen. Ik moet het dus in de code daarvoor zoeken lijkt me.

Acties:
  • 0 Henk 'm!

  • Creepy
  • Registratie: Juni 2001
  • Laatst online: 13-10 23:09

Creepy

Tactical Espionage Splatterer

Als je support op code van een ander wilt heben, dan zul je toch echt in eerste instantie het bij die ander moeten proberen. Hier in PRG draait het om het zelf programmeren. Een gedownload script hier neerzetten en hopen dat wij de fouten er voor je gaan uithalen is nu net niet de bedoeling.

"I had a problem, I solved it with regular expressions. Now I have two problems". That's shows a lack of appreciation for regular expressions: "I know have _star_ problems" --Kevlin Henney

Pagina: 1

Dit topic is gesloten.