DouglasMoody
DouglasMoody

Reputation: 28

What is method to use foreach on a txt file?

Below embedded foreach commands needs $user to come from list.txt, dump groups from AD into $user.txt file and remove.

How do I specify $user as each line in the list.txt whild also verifying the formatting of the list inside the list.txt is just one name per line, no comma?

foreach ($user in .\list.txt) {
    $groups = (Get-ADUser $user -Properties MemberOf).MemberOf
    Add-Content -Path C:\TEMP\RemoveGroups\$user.txt -Value $groups
    foreach ($group in $groups) {
        Remove-ADGroupMember $group -Member $user
    }

Upvotes: 0

Views: 1050

Answers (2)

BiaoGuo
BiaoGuo

Reputation: 39

$List = Get-Content .\List.txt
Foreach ($User in $List){
    $Groups = (Get-ADUser $user -Properties MemberOf).MemberOf

    Foreach ($GroupDN in $Groups){
        Try {
            $Group = Get-ADGroup $GroupDN
            Remove-ADGroupMember $Group -member $user -ErrorAction Stop
            $Succeed = $Succeed,$Group.Name -join ";"
        }
        Catch {
            $Failed = $Failed,$Group.Name -Join ";"
        }
    }

    $temp = New-Object psobject -ArgumentList @{
        User    = $User
        Succeed = $Succeed
        Failed  = $Failed
    }

    Export-Csv -InputObject $temp -Path C:\TEMP\RemoveGroups\Result.csv -Encoding UTF8 -NoTypeInformation -Append
}

You will get the CSV file like this:

User,Succeed,Failed

user1,Group1;Group2,Group3;Group4

user2,Group2;Group3,Group1;Group4

Upvotes: 2

ekeeling
ekeeling

Reputation: 381

You can use the following code.

# Read the list of users to an array of strings.
$users = Get-Content .\list.txt
foreach ($user in $users) {
    # Validate that the username only contains a-z and 0-9.
    if ($user -match "^[a-zA-Z0-9]+$") {
        $groups = (Get-ADUser $user -Properties MemberOf).MemberOf
        Add-Content -Path C:\TEMP\RemoveGroups\$user.txt -Value $groups
        foreach ($group in $groups) {
            Remove-ADGroupMember $group -member $user
        }
    }
}

Upvotes: 1

Related Questions