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?