Home > OS >  The -Match switch is not working as expected
The -Match switch is not working as expected

Time:09-23

I'm using quser to get rdp session in disconnected stated

The -match is not working as i expected '$env:USERNAME' is ignore

$computers = 'computer1','computer2','computer3','computer4'

foreach ($computer in $computers){

quser /server:$computer | ? { $_ -match “Disc” -and '$env:USERNAME'}|foreach {
$Session = ($_ -split ‘  ’)[2]
$user = ($_ -split ‘  ’)[1]
$idletime= ($_ -split ‘  ’)[4]
logoff /SERVER:$computer $Session 
}}

CodePudding user response:

The -and operator is a boolean logic operator - it evaluates the expressions on either side, coerces them to a [bool] (eg. $true or $false), and then returns $true if, and only if both expressions evaluated to $true.

Coercing a non-empty string (like '$env:USERNAME') to [bool] invariably results in $true:

PS ~> [bool]'$env:USERNAME'
True

So the condition you're effectively evaluating is:

($_ -match "Disc") -and $true

Which is logically the exact same as just doing:

$_ -match "Disc"

on its own.

If you want to perform 2 -match comparisons and ensure they're both true, you'll want to change the expression to:

... |? { $_ -match "disc" -and $_ -match $env:USERNAME } | ...

Notice that I'm not surrounding $env:USERNAME in '' - quoting it in single quotes creates a string with the literal value $env:USERNAME (which is not a valid account name in windows)

  • Related