# Exclude OU groups in powershell script

**URL:** https://forums.powershell.org/t/exclude-ou-groups-in-powershell-script/11347
**Category:** PowerShell Help
**Created:** [September 21, 2018, 7:47am UTC](https://forums.powershell.org/t/exclude-ou-groups-in-powershell-script/11347 "2018-09-21T07:47:38Z")
**Posts on this page:** 10
**Page:** 1

<div class="post-metadata">

### Author: ![arjo](https://avatars.discourse-cdn.com/v4/letter/a/87869e/32.png) [@arjo](https://forums.powershell.org/u/arjo)
#### Post date: [September 21, 2018, 7:47am UTC](https://forums.powershell.org/t/exclude-ou-groups-in-powershell-script/11347/1 "2018-09-21T07:47:38Z")

</div>

Hello,

we have a powershell script that looks every day if users in the domain have a password that needs to be changed, if so the user receives a email for changing password)

The script looks for every user in all ou’s but we want to exclude some ou’s in the script.

The script/ import module we use is

import-module ActiveDirectory

$verbose = $true

$notificationstartday = 14

$sendermailaddress = “[example@example.net](mailto:example@example.net)”

$SMTPserver = “example@example.nl”

$DN = “OU=customers,DC=customerdomain,DC=local”

under the OU=customers we want to exclude some OU’s

if we use

$ExcludeGroup =“OU=users,OU=customer1,OU=customers,DC=customerdomain,DC=local”

it does not exclude the accounts in the OU

&nbsp;

regards

---

<div class="post-metadata">

### Author: ![sanchez](https://avatars.discourse-cdn.com/v4/letter/s/35a633/32.png) [@sanchez](https://forums.powershell.org/u/sanchez)
#### Post date: [September 21, 2018, 8:09am UTC](https://forums.powershell.org/t/exclude-ou-groups-in-powershell-script/11347/2 "2018-09-21T08:09:58Z")

</div>

Is this the full code? Because I do not see anything in there where you search, or how you’re excluding.

---

<div class="post-metadata">

### Author: ![arjo](https://avatars.discourse-cdn.com/v4/letter/a/87869e/32.png) [@arjo](https://forums.powershell.org/u/arjo)
#### Post date: [September 21, 2018, 8:31am UTC](https://forums.powershell.org/t/exclude-ou-groups-in-powershell-script/11347/3 "2018-09-21T08:31:17Z")

</div>

Hello Jon, this is the hole script (i deleted some info), thanks for helping

import-module ActiveDirectory

&nbsp;

##############Variables#################

&nbsp;

$verbose = $true

&nbsp;

$notificationstartday = 14

&nbsp;

$sendermailaddress = “[example@example.net](mailto:example@example.net)”

&nbsp;

$SMTPserver = “servername”

&nbsp;

$DN = “OU=Customers,DC=Domain,DC=local”

&nbsp;

$ExcludeGroup = “OU=Users,OU=company1,OU=Customers,DC=Domain,DC=local”

&nbsp;

&nbsp;

########################################

&nbsp;

##############Function##################

&nbsp;

function PreparePasswordPolicyMail ($ComplexityEnabled,$MaxPasswordAge,$MinPasswordAge,$MinPasswordLength,$PasswordHistoryCount)

&nbsp;

{

$verbosemailBody = “`r`n`r`n”

&nbsp;

$verbosemailBody += “`r`n`r`n”

&nbsp;

$verbosemailBody += “`r`n”

$verbosemailBody += “- `r`n”

$verbosemailBody += “`r`n”

$verbosemailBody += “`r`n`r`n”

&nbsp;

return $verbosemailBody

}

&nbsp;

function SendMail ($SMTPserver,$sendermailaddress,$usermailaddress,$mailBody)

&nbsp;

{

&nbsp;

$smtpServer = $SMTPserver

&nbsp;

$msg = new-object Net.Mail.MailMessage

&nbsp;

$smtp = new-object Net.Mail.SmtpClient($smtpServer)

&nbsp;

$msg.From = $sendermailaddress

&nbsp;

$msg.To.Add($usermailaddress)

&nbsp;

$msg.Subject = “Password expires”

&nbsp;

$msg.Body = $mailBody

&nbsp;

$smtp.Send($msg)

&nbsp;

}

&nbsp;

########################################

&nbsp;

##############Main######################

&nbsp;

$domainPolicy = Get-ADDefaultDomainPasswordPolicy

&nbsp;

$passwordexpirydefaultdomainpolicy = $domainPolicy.MaxPasswordAge.Days -ne 0

&nbsp;

if ($passwordexpirydefaultdomainpolicy)

&nbsp;

{

&nbsp;

$defaultdomainpolicyMaxPasswordAge = $domainPolicy.MaxPasswordAge.Days

&nbsp;

if ($verbose)

&nbsp;

{

&nbsp;

$defaultdomainpolicyverbosemailBody = PreparePasswordPolicyMail $PSOpolicy.ComplexityEnabled $PSOpolicy.MaxPasswordAge.Days $PSOpolicy.MinPasswordAge.Days $PSOpolicy.MinPasswordLength $PSOpolicy.PasswordHistoryCount

&nbsp;

}

&nbsp;

}

&nbsp;

foreach ($user in (Get-ADUser -SearchBase $DN -Filter \* -properties mail))

&nbsp;

{

&nbsp;

$samaccountname = $user.samaccountname

&nbsp;

$PSO= Get-ADUserResultantPasswordPolicy -Identity $samaccountname

&nbsp;

if ($PSO -ne $null)

&nbsp;

{

&nbsp;

$PSOpolicy = Get-ADUserResultantPasswordPolicy -Identity $samaccountname

&nbsp;

$PSOMaxPasswordAge = $PSOpolicy.MaxPasswordAge.days

&nbsp;

$pwdlastset = [datetime]::FromFileTime((Get-ADUser -LDAPFilter “(&(samaccountname=$samaccountname))” -properties pwdLastSet).pwdLastSet)

&nbsp;

$expirydate = ($pwdlastset).AddDays($PSOMaxPasswordAge)

&nbsp;

$delta = ($expirydate - (Get-Date)).Days

&nbsp;

$comparionresults = (($expirydate - (Get-Date)).Days -le $notificationstartday) -AND ($delta -ge 1)

&nbsp;

if ($comparionresults)

&nbsp;

{

&nbsp;

$mailBody = "Beste " + $user.GivenName + “,`r`n`r`n”

&nbsp;

$mailBody += “`r`n`r`n”

&nbsp;

if ($verbose)

&nbsp;

{

$mailBody += PreparePasswordPolicyMail $PSOpolicy.ComplexityEnabled $PSOpolicy.MaxPasswordAge.Days $PSOpolicy.MinPasswordAge.Days $PSOpolicy.MinPasswordLength $PSOpolicy.PasswordHistoryCount

}

$mailBody += “`r`n`r`n”

&nbsp;

$mailBody += “`r`n`r`n”

&nbsp;

$usermailaddress = $user.mail

&nbsp;

SendMail $SMTPserver $sendermailaddress $usermailaddress $mailBody

&nbsp;

}

&nbsp;

}

&nbsp;

else

&nbsp;

{

&nbsp;

if ($passwordexpirydefaultdomainpolicy)

&nbsp;

{

&nbsp;

$pwdlastset = [datetime]::FromFileTime((Get-ADUser -LDAPFilter “(&(samaccountname=$samaccountname))” -properties pwdLastSet).pwdLastSet)

&nbsp;

$expirydate = ($pwdlastset).AddDays($defaultdomainpolicyMaxPasswordAge)

&nbsp;

$delta = ($expirydate - (Get-Date)).Days

&nbsp;

$comparionresults = (($expirydate - (Get-Date)).Days -le $notificationstartday) -AND ($delta -ge 1)

&nbsp;

if ($comparionresults)

&nbsp;

{

&nbsp;

$mailBody = "Beste " + $user.GivenName + “,`r`n`r`n”

&nbsp;

$delta = ($expirydate - (Get-Date)).Days

&nbsp;

$mailBody += “`r`n`r`n”

&nbsp;

if ($verbose)

&nbsp;

{

$mailBody += $defaultdomainpolicyverbosemailBody

}

&nbsp;

$mailBody += “`r`n`r`n”

&nbsp;

$mailBody += “`r`n`r`n”

&nbsp;

$usermailaddress = $user.mail

&nbsp;

SendMail $SMTPserver $sendermailaddress $usermailaddress $mailBody

&nbsp;

}

&nbsp;

}

&nbsp;

}

&nbsp;

}

---

<div class="post-metadata">

### Author: ![sanchez](https://avatars.discourse-cdn.com/v4/letter/s/35a633/32.png) [@sanchez](https://forums.powershell.org/u/sanchez)
#### Post date: [September 21, 2018, 8:38am UTC](https://forums.powershell.org/t/exclude-ou-groups-in-powershell-script/11347/4 "2018-09-21T08:38:22Z")

</div>

Please see the text in bold at the top of every post on how to format code for the forums " **To format code…"**

---

<div class="post-metadata">

### Author: ![arjo](https://avatars.discourse-cdn.com/v4/letter/a/87869e/32.png) [@arjo](https://forums.powershell.org/u/arjo)
#### Post date: [September 21, 2018, 9:22am UTC](https://forums.powershell.org/t/exclude-ou-groups-in-powershell-script/11347/5 "2018-09-21T09:22:17Z")

</div>

```
import-module ActiveDirectory

##############Variables#################

$verbose = $true

$notificationstartday = 14

$sendermailaddress = "example@example.net"

$SMTPserver = "servername"

$DN = "OU=Customers,DC=Domain,DC=local"

$ExcludeGroup = "OU=Users,OU=company1,OU=Customers,DC=Domain,DC=local"

########################################

##############Function##################

function PreparePasswordPolicyMail ($ComplexityEnabled,$MaxPasswordAge,$MinPasswordAge,$MinPasswordLength,$PasswordHistoryCount)

{
                $verbosemailBody = "`r`n`r`n"

		$verbosemailBody += "`r`n`r`n"

		$verbosemailBody += "`r`n"
		$verbosemailBody += "- `r`n"
		$verbosemailBody += "`r`n"
		$verbosemailBody += "`r`n`r`n"
		
		return $verbosemailBody
}

function SendMail ($SMTPserver,$sendermailaddress,$usermailaddress,$mailBody)

{

        $smtpServer = $SMTPserver

        $msg = new-object Net.Mail.MailMessage

        $smtp = new-object Net.Mail.SmtpClient($smtpServer)

        $msg.From = $sendermailaddress

        $msg.To.Add($usermailaddress)

                $msg.Subject = "Password expires"

        $msg.Body = $mailBody

        $smtp.Send($msg)

}

########################################

##############Main######################

$domainPolicy = Get-ADDefaultDomainPasswordPolicy

$passwordexpirydefaultdomainpolicy = $domainPolicy.MaxPasswordAge.Days -ne 0

if ($passwordexpirydefaultdomainpolicy)

{

                $defaultdomainpolicyMaxPasswordAge = $domainPolicy.MaxPasswordAge.Days

                if ($verbose)

                {

                                $defaultdomainpolicyverbosemailBody = PreparePasswordPolicyMail $PSOpolicy.ComplexityEnabled $PSOpolicy.MaxPasswordAge.Days $PSOpolicy.MinPasswordAge.Days $PSOpolicy.MinPasswordLength $PSOpolicy.PasswordHistoryCount

                }

}

foreach ($user in (Get-ADUser -SearchBase $DN -Filter * -properties mail))

{

                $samaccountname = $user.samaccountname

                $PSO= Get-ADUserResultantPasswordPolicy -Identity $samaccountname

                if ($PSO -ne $null)

                {             

                                $PSOpolicy = Get-ADUserResultantPasswordPolicy -Identity $samaccountname

                                $PSOMaxPasswordAge = $PSOpolicy.MaxPasswordAge.days

                                $pwdlastset = [datetime]::FromFileTime((Get-ADUser -LDAPFilter "(&(samaccountname=$samaccountname))" -properties pwdLastSet).pwdLastSet)

                                $expirydate = ($pwdlastset).AddDays($PSOMaxPasswordAge)

                                $delta = ($expirydate - (Get-Date)).Days

                                $comparionresults = (($expirydate - (Get-Date)).Days -le $notificationstartday) -AND ($delta -ge 1)

                                if ($comparionresults)

                                {

                                                $mailBody = "Beste " + $user.GivenName + ",`r`n`r`n"

                                                $mailBody += "`r`n`r`n"

                                                if ($verbose)

                                                {
                                                                $mailBody += PreparePasswordPolicyMail $PSOpolicy.ComplexityEnabled $PSOpolicy.MaxPasswordAge.Days $PSOpolicy.MinPasswordAge.Days $PSOpolicy.MinPasswordLength $PSOpolicy.PasswordHistoryCount
                                                }
						$mailBody += "`r`n`r`n"

                                                $mailBody += "`r`n`r`n"

                                                $usermailaddress = $user.mail

                                                SendMail $SMTPserver $sendermailaddress $usermailaddress $mailBody

                                }

                }

                else

                {

                                if ($passwordexpirydefaultdomainpolicy)

                                {

                                                $pwdlastset = [datetime]::FromFileTime((Get-ADUser -LDAPFilter "(&(samaccountname=$samaccountname))" -properties pwdLastSet).pwdLastSet)

                                                $expirydate = ($pwdlastset).AddDays($defaultdomainpolicyMaxPasswordAge)

                                                $delta = ($expirydate - (Get-Date)).Days

                                                $comparionresults = (($expirydate - (Get-Date)).Days -le $notificationstartday) -AND ($delta -ge 1)

                                                if ($comparionresults)

                                                {

                                                                $mailBody = "Beste " + $user.GivenName + ",`r`n`r`n"

                                                                $delta = ($expirydate - (Get-Date)).Days

                                                                $mailBody += "`r`n`r`n"

                                                                if ($verbose)

                                                                {
                                                                                $mailBody += $defaultdomainpolicyverbosemailBody
                                                                }

                                                                $mailBody += "`r`n`r`n"
								
								$mailBody += "`r`n`r`n"

                                                                $usermailaddress = $user.mail

                                                                SendMail $SMTPserver $sendermailaddress $usermailaddress $mailBody

                                                }

                                }

                }

}
```

---

<div class="post-metadata">

### Author: ![sanchez](https://avatars.discourse-cdn.com/v4/letter/s/35a633/32.png) [@sanchez](https://forums.powershell.org/u/sanchez)
#### Post date: [September 21, 2018, 9:48am UTC](https://forums.powershell.org/t/exclude-ou-groups-in-powershell-script/11347/6 "2018-09-21T09:48:43Z")

</div>

How are you attempting to exclude them? You have the variable defined, but you aren’t implementing it anywhere else in the code.

---

<div class="post-metadata">

### Author: ![arjo](https://avatars.discourse-cdn.com/v4/letter/a/87869e/32.png) [@arjo](https://forums.powershell.org/u/arjo)
#### Post date: [September 21, 2018, 11:45am UTC](https://forums.powershell.org/t/exclude-ou-groups-in-powershell-script/11347/7 "2018-09-21T11:45:19Z")

</div>

i dont have a lott knowledge about powershell, do you know what code i can use and where to put it in the script? takes for your time!

---

<div class="post-metadata">

### Author: ![david-schmidtberger](https://avatars.discourse-cdn.com/v4/letter/d/ba9def/32.png) [@david-schmidtberger](https://forums.powershell.org/u/david-schmidtberger)
#### Post date: [September 21, 2018, 2:28pm UTC](https://forums.powershell.org/t/exclude-ou-groups-in-powershell-script/11347/8 "2018-09-21T14:28:34Z")

</div>

Unfortunately, I’m not aware of a “reverse” searchbase…

and to make things more annoying, you can’t use distinguishedname as a filter.

so when I need to exclude users in specific OU’s from a script, I generally perform an if statement on the users distinguished name.

ie something like:

```
foreach ($user in (Get-ADUser -SearchBase $DN -Filter * -properties mail))

{

if ($user.distinguishedname -notlike "*company1*")

{

do something

}

else

{

do nothing

}
```

---

<div class="post-metadata">

### Author: ![ni-pfe](https://avatars.discourse-cdn.com/v4/letter/n/b782af/32.png) [@ni-pfe](https://forums.powershell.org/u/ni-pfe)
#### Post date: [September 21, 2018, 2:44pm UTC](https://forums.powershell.org/t/exclude-ou-groups-in-powershell-script/11347/9 "2018-09-21T14:44:19Z")

</div>

My first thought would be to gather all the OUs in the environment and then loop through them with foreach. You could then use an If statement to exclude OUs. Something like the below.

```
$OUs = Get-ADOrganizationalUnit -Filter *

foreach($OU in $OUs){
    if($OU.DistinguishedName -ne "OU=EXCLUDE,OU=Contoso,DC=Contoso,DC=com"){
        $Users = Get-ADUser -Filter 'Enabled -eq $true' -SearchBase $OU.DistinguishedName
        foreach($User in $Users){
            if($User.PasswordLastSet -lt (Get-Date).AddDays(-60)){
                Send-MailMessage -To user@contoso.com -From administrator@contoso.com -Subject 'Password Expiry' -SmtpServer relay.contoso.com
            }
        }
    }
}
```

---

<div class="post-metadata">

### Author: ![dotnVo](https://avatars.discourse-cdn.com/v4/letter/d/4af34b/32.png) [@dotnVo](https://forums.powershell.org/u/dotnVo)
#### Post date: [May 16, 2024, 8:34pm UTC](https://forums.powershell.org/t/exclude-ou-groups-in-powershell-script/11347/10 "2024-05-16T20:34:22Z")

</div>


