Remove group member if file exists

mara2021 1,121 Reputation points
2022-08-23T17:11:51.11+00:00

I am trying to remove members from a local group created on our computers if a file does not exist.
This is for another project I am working on. The file will be a timestamp as to when the
user was added to the group. We have a script that will add the user to the group and create a file for the user. I want to remove users added manually and not using the program. I am receiving an error on $TempGroup.remove($User.Path) What am I missing? I uploaded the script as an image because the Azure Firewall did not like something in the script and it was blocked. Any help would be appreciated. Thank you.

234126-script.jpg

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Andreas Baumgarten 123.4K Reputation points MVP Volunteer Moderator
    2022-08-23T19:14:37.3+00:00

    Hi @mara2021 ,

    if you want to get the members of a local group on your computer please try this script:

    $groupName = "Testgroup"  
    $filePath = "C:\Junk\"  
    $userlist = $((Get-LocalGroupMember -Group "$groupName").Name).Replace("$env:COMPUTERNAME\", "")  
    $userlist | ForEach-Object {  
        if (Test-Path $filePath\$_.txt -PathType Leaf) {  
            Write-Output "$_ user file exists"  
        }  
        else {  
            Write-Output "$_ user file does not exists .... removing user from local group"   
            Remove-LocalGroupMember -Group "$groupName" -Member $_ -WhatIf   
        }  
    }  
    

    The -WhatIf parameter in line 10 will show what will happen, but will not remove the user from group. If everything is like expected just remove the -WhatIf parameter in line 10 and the user will be removed from the group

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2022-08-25T18:20:24.783+00:00

    The problem is that your user value is a string and strings don't have a property named "Path".


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.