Home > front end >  Powershell: Not working? $list = $list | Where-Object Name -NotContains $myPSCustomObject
Powershell: Not working? $list = $list | Where-Object Name -NotContains $myPSCustomObject

Time:06-30

I'm trying to use the output of Get-LoggedOnUser.ps1 (which outputs a PSCustomObject) to filter a list of usernames.

Goal: I want to remove from my list any currently logged on users. However, I cannot figure what I'm doing isn't working, even debugging in the ISE. You can see I've even tried to make the object's field names match eachother.

$currentlyLoggedInUsernames = .\Get-LoggedOnUser.ps1
$currentlyLoggedInUsernames = .\Get-LoggedOnUser.ps1 | Select-Object UserName, LogonTime | sort UserName, LogonTime
$currentlyLoggedInUsers = $currentlyLoggedInUsernames | Select-Object UserName | Select-Object @{Name = "Name"; Expression = {$_.UserName}}

$useraccounts = Get-ChildItem -path \\$env:COMPUTERNAME\c$\users\ -Exclude 'public', 'Administrator' | Where-Object Name -notcontains $env:USERNAME 
### Trouble below ###
$useraccounts = $useraccounts | Where-Object Name -NotContains $currentlyLoggedInUsers #BUT OTHER CURRENTLY LOGGED IN USERS REMAIN AFTER THIS LINE IS RUN.
$useraccounts #Why doesn't the above line actually remove the other logged in users from the list?

CodePudding user response:

-notcontains is to be used when you want to check a collection against a value. In your case, you are checking a value against a collection (the opposite). You need to use -notiné

Example

# To check if a value is in a collection
"A" -in @('A','B','C')

# To check if a collection contains a value.
@('A','B','C') -contains 'A'

Here is your sample code, simplified and revised.

$currentlyLoggedInUsers = .\Get-LoggedOnUser.ps1
$useraccounts = Get-ChildItem -path \\$env:COMPUTERNAME\c$\users\ -Exclude 'public', 'Administrator' | Where-Object Name -notcontains $env:USERNAME 

$NotLoggedInUsers = $useraccounts | Where-Object Name -notin $currentlyLoggedInUsers.Username

References

About_Comparison_Operators

  • Related