Dan Goodwin
Dan Goodwin

Reputation: 57

If user belongs to this group, show this, if not, show this

I am a novice to powershell and starting to learn the syntax and what logic is needed, but I have given this a good go.

I need to pop in a conditional field that does the below

But my script doesn't quite do this and I wandered how my script could be changed to get what I need it to do.

This is my script below:

Import-Module ActiveDirectory

$OUPath = "OU=1_Users,DC=DGDomain,DC=Local"

$filepath = "C:\temp\users.csv"

$readonlygroup = "ReadOnlyAccess"
$readonlygroupmembers = Get-ADGroupMember -Identity $readonlygroup | Get-ADUser -Properties SamAccountName | Select SamAccountName

$admingroup = "Domain Admins"
$admingroupmembers = Get-ADGroupMember -Identity $admingroup | Get-ADUser -Properties SamAccountName | Select SamAccountName

$users = Get-ADUser -Filter * -Properties * -SearchBase $OUPath |
         Where-Object { $_.Enabled -eq $true } |
         Select SamAccountName

Get-ADUser -Filter * -Properties * -SearchBase $OUPath |
Where-Object { $_.Enabled -eq $true } |
Select SamAccountName,
       DisplayName,
       @{Label = "Access Level"
            Expression =  {
                    foreach ($user in $users) {
                        if ($readonlygroupmembers -contains $users)
                            { "Read Only" }
                        else {
                            if ($admingroupmembers -contains $users)
                                { "Administrator" }
                            else
                                { "None" }
                            }
                        } } } |

Export-csv $filepath -NoTypeInformation

Upvotes: 0

Views: 74

Answers (1)

Ivan Mirchev
Ivan Mirchev

Reputation: 839

This should do the trick:

$OUPath = "OU=1_Users,DC=DGDomain,DC=Local"

$filepath = "C:\temp\users.csv"

$readonlygroup = "ReadOnlyAccess"
$readonlygroupmembers = (Get-ADGroupMember -Identity $readonlygroup | Get-ADUser -Properties SamAccountName).SamAccountName

$admingroup = "Domain Admins"
$admingroupmembers = (Get-ADGroupMember -Identity $admingroup | Get-ADUser -Properties SamAccountName).SamAccountName

$users = Get-ADUser -Filter { Enabled -eq $true } -SearchBase $OUPath -Properties DisplayName

foreach ($user in $users) {
    if ($user.SamAccountName -in $admingroupmembers) { $groupMembership = 'DomainAdmin'}
    elseif ($user.SamAccountName -in $readonlygroupmembers) { $groupMembership = 'ReadOnly' }
    else {$groupMembership = 'None'}
    [PSCustomObject]@{
        DisplayName = $user.DisplayName
        SamAccountName = $user.SamAccountName
        AccessLevel = $groupMembership

    }
}

Export-csv $filepath -NoTypeInformation

Upvotes: 1

Related Questions