Reputation: 5
Have a problem which seems to be to simple, but I can not crack.
I have 3 Files with a content of Usernames. I want to see which users match in File1 and File2/File3. I would then write the users that match, into another file.
The problem is my if statement, it doesnt give me any values back / its never true. If I look for a random user that is in File 1 if (User -in $MDM_USER) {Add-Content "C:\temp\MDM\USER_without_VPN.txt"}
" its working, but not as a $file variable.
Even if there is another way to get the same result, I would really appreciate if somebody could tell me what my mistake is.
$VPN_USER = Get-Content "C:\temp\MDM\Alle Benutzer mit VPN.txt"
$IT_USER = Get-Content "C:\temp\MDM\Alle_IT_Benutzer.txt"
$MDM_USER = Get-Content "C:\temp\MDM\alle_MDM-ios_user.txt"
foreach ($file in $IT_USER)
{
if ($file -in $MDM_USER) {Add-Content "C:\temp\MDM\IT_USER_with_VPN.txt"}
}
Upvotes: 0
Views: 903
Reputation: 25001
Using Compare-Object seems like an easier solution:
# it.txt users
user4
user5
user6
user2
user3
# vpn.txt users
user1
user2
user3
# mdm.txt users
user1
user5
user7
user3
user10
$it_users = Get-Content it.txt
$vpn_users = Get-Content vpn.txt
$mdm_users = Get-Content mdm.txt
Compare-Object $it_users $vpn_users -IncludeEqual -ExcludeDifferent -PassThru |
Set-Content it_and_vpn.txt
Compare-Object $it_users $mdm_users -IncludeEqual -ExcludeDifferent -PassThru |
Set-Content it_and_mdm.txt
Results:
PS> Get-Content it_and_mdm.txt
user5
user3
PS> Get-Content it_and_vpn.txt
user2
user3
Explanation:
By default, Compare-Object
outputs differences between the reference and difference objects. You must use -IncludeEqual
and -ExcludeDifferent
in Windows PowerShell to only see equal objects from both lists. -PassThru
outputs just the input objects (the compared objects) instead of the custom object typically created by Compare-Object
.
Your logic seems correct with your approach. However, you have an extra set of {}
around the Add-Content
command. This creates a script block, and you did not call that script block, which results in Add-Content
never being called. See below for an example of the behavior.
PS> { Get-Content vpn.txt } # Only outputs script block contents as a string
Get-Content vpn.txt
PS> & { Get-Content vpn.txt } # & calls the script block
user1
user2
user3
Upvotes: 2