Home > OS >  Powershell filtering PSCsutomobjects
Powershell filtering PSCsutomobjects

Time:01-10

I would like to ask you for help with getting/filtering informations from the array/pscustomobjects.

I have this command:

$queryResults = (qwinsta /server:$server | foreach { (($_.trim() -replace "\s ",","))} | ConvertFrom-Csv) 

which gives me back something like this:

SESSIONNAME : rdp-tcp#1
USERNAME    : tnejtek
ID          : 3
STATE       : Active
TYPE        : 
DEVICE      : 

SESSIONNAME : console
USERNAME    : 5
ID          : Conn
STATE       : 
TYPE        : 
DEVICE      : 

SESSIONNAME : rdp-tcp
USERNAME    : 65536
ID          : Listen
STATE       : 
TYPE        : 
DEVICE      : 

Now I would like to be able to set the conditions with if statement based on the connected user and its session state. For example, if username is tnejtek and state is active then write "tnejtek is connected", if the username would be "xxx" and session state would be disconnected, write "user xxx is disconnected"

Currently I tried this

   if 
   (($queryResults -match "tnejtek") -and ($queryResults -match "Active")) {
  
   write-host "tnejtek is connected"
   }
   else {
   "user not found"
   }

but this is not working, because I am able to check that in variable $queryResults is user tnejtek, but I dont know how to check directly if his user state is active or not, in the example I am checking that tnejtek is there and that some session has state active.

Thank you very much

CodePudding user response:

One way would be to look for both on the same line, although this doesn't take advantage of any properties:

if ($queryResults -match 'tnejtek|active') {
  write-host "tnejtek is connected"
}
else {
  'user not found'
}

Or (any result becomes true)

if ($queryResults | where {$_.username -eq 'tnejtek' -and $_.state -eq 'active') {
  write-host "tnejtek is connected"
}
else {
  'user not found'
}

CodePudding user response:

If I understood correctly, you're looking to check for a specific user (defined previously) on the qwinsta result, and if the user is found and the state of the user is one of the states defined previously, display said user and it's details, else return a message saying that the user was not found.

# States should be the exact word to match
$validstates = 'Active', 'Idle', 'Disconnected'
$user = 'tnejtek'

qwinsta /server:$server | ForEach-Object { $_.Trim() -replace "\s ","," } |
ConvertFrom-Csv | Where-Object {
    $_.Username -match $user -and $_.State -in $validstates
} | & {
    process
    {
        if(-not $_) { return "$user is not found!" }
        'ID: {0} - Username: {1} - State: {2}' -f $_.ID, $_.Username, $_.State
    }
}
  •  Tags:  
  • Related