0

I'm making a PowerShell script that will list the number of users currently logged on to a system.

What I do is the following:

$users = query user /server:localhost
$number = $users.Count

if ( $number -le 1 ) {
    Write-Host 0 Users online"|" Users=0
} else {
    $number = $users.Count-1
    Write-Host $number Users online"|" Users=$number
}
exit

However I need to be able to exclude users, such as the Administrator.

I thought I could make an if statement but I don't know how to do this properly really.

Lets say I do it like this:

$users = query user /server:localhost

if ($users -contains '*Administrator*') {
    $number = $users.Count-2
    Write-Host $number
}
exit

I add the .Count-2 because the first line is the information such as "Username, ID, Session" etc.

It doesn't return anything so I don't think I can make an if statement like that.

Is it possible to "grep" something from the $users variable and delete that line?

For instance, if I run:

$users[1]

It will return the second line etc. But how do I manipulate the lines?

I also tried:

$users | Where-Object {$_ -match 'administrator'}

But that returns nothing.

Does anyone have any input here on what I could do?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
PatricF
  • 379
  • 2
  • 5
  • 15
  • 3
    Try `$users | Where-Object {$_ -notlike "*Administrator*"}` – Paxz Aug 03 '18 at 12:24
  • Holy crap that was fast. That actually worked. Thank you very much! – PatricF Aug 03 '18 at 12:26
  • No problem :) Need a greater explanation or figured it out yourself? – Paxz Aug 03 '18 at 12:27
  • I think I can figure it out from here. That was the piece I was missing. Thank you! – PatricF Aug 03 '18 at 12:28
  • You might consider it overkill but [this function](https://stackoverflow.com/a/29130697/38294070) should convert that output to a customer powershell object. Its what I use for converting text based output like what you have. – Matt Aug 03 '18 at 13:46

1 Answers1

0

It doesn't return anything so I don't think I can make an if statement like that.

You can make an if statement roughly like that, but what you can't do is use:

'some words test' -contains 'words'

as the test. This is because -contains is for this use:

@('collection', 'of', 'words', 'here') -contains 'words'     # if a collection contains X.

For text inside a string, you need one of the following:

'some words test' -like '*words*'   # this is a wildcard match, case insensitive.

#or

'some words test' -match 'words'    # this is a regex match, case insensitive.

#or

'some words test'.Contains('words')    # this is a .Net method on strings, case sensitive.
TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87