NealR
NealR

Reputation: 10709

Determine if user is member of local group in Powershell

Below are my two best guess at finding out if our service account is a member of the IIS_IUSRS local group.

Neither will crash, however each if statment returns false each and every time. I've manually added/removed the user account to the group and verified that this is a "false" negative.

#Connect to Active Directory database using Powershell ADSI  adapter
#Keep this value as 'localhost' to ensure you connect to this computer
$cn = [ADSI]"WinNT://localhost"
$env = "dev"
$monet = "s.Monet.$env"
$periscope = "s.PeriscopeWeb.$env"
$agentData = "s.AgentData.$env"

#add service accounts to IIS_IUSRS group
$iis_iusrs = [ADSI] "WinNT://localhost/IIS_IUSRS"

if (-not $iis_iusrs.memberOf | where { $_ -match $monet})
{
    $iis_iusrs.Add("WinNT://DOMAIN/$monet, user")
}    
if (-not (Get-ADUser $periscope -Properties memberof).memberof -like "CN=IIS_IUSRS*")
{

Upvotes: 3

Views: 2987

Answers (1)

Nathan Rice
Nathan Rice

Reputation: 3111

This might be what you're looking for:

#Get the IIS_IUSRS group
$iis_iusrs = [ADSI]"WinNT://localhost/IIS_IUSRS"
$Members = @($iis_iusrs.psbase.Invoke("Members"))
#Populate the $MemberNames array with all the user ID's
$MemberNames = @()
$Members | ForEach-Object {$MemberNames += $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null);}

#See if your user ID is in there
if (-Not $MemberNames.Contains($monet)) {
    $iis_iusrs.Add("WinNT://DOMAIN/$monet, user")
}

Upvotes: 4

Related Questions