PowerShell add users to group based on OU - Schedule script

Hello,

I am trying to schedule a script to run that will only add users to a security group based on the OU they are in. I keep on getting these errors. This is my first attempt at creating a Powershell script so forgive my errors in the code.

Import-Module ActiveDirectory

$OU1 = 'OU=Test_Group,OU=Priviledged_Access,OU=_Users,DC=domain,DC=org'
$SecGroup = (Get-ADGroup -Identity 'PasswordPolicy').DistinguishedName

Get-ADUser –SearchBase $OU1 –LDAPFilter (&(objectCategory=person)(objectClass=user)!(memberOf=$SecGroup)) | ForEach-Object {Add-ADPrincipalGroupMembership -Identity $_ –MemberOf "$SecGroup"}
Peter CopeAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Subash SundharanIT Infrastructure Architect Commented:
Probably the LDAP filter error.. Try this..
Get-ADUser –SearchBase $OU1 –LDAPFilter "(&(objectCategory=person)(objectClass=user)(!(memberOf=$SecGroup)))"  | Add-ADPrincipalGroupMembership –MemberOf "$SecGroup"

Open in new window

If it doesn't work then post the error from PowerShell console..
Peter CopeAuthor Commented:
This is the error that i am getting.

PS C:\scripts> .\Write_PA_PasswordPolicy.ps1
At C:\scripts\Write_PA_PasswordPolicy.ps1:48 char:171
+ ... erOf "$SecGroup"
+                    ~
The string is missing the terminator: ".
At C:\scripts\Write_PA_PasswordPolicy.ps1:47 char:1
+ {
+ ~
Missing closing '}' in statement block.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
Subash SundharanIT Infrastructure Architect Commented:
The string is missing the terminator: ".

Missing closing '}' in statement block.
Errors indicate a syntax error, are you using the code which I posted? If not please post the exact code which you are using..
Cloud as a Security Delivery Platform for MSSPs

Every Managed Security Service Provider (MSSP) needs a platform to deliver effective and efficient security-as-a-service to their customers. Scale, elasticity and profitability are a few of the many features that a Cloud platform offers. View our on-demand webinar to learn more!

Peter CopeAuthor Commented:
This is the code of the entire file. I was trying to add logging to the file but was confused on how to do that.


.PARAMETER <Parameter_Name>
    <Brief description of parameter input required. Repeat this attribute if required>
.INPUTS
  <Inputs if any, otherwise state None>
.OUTPUTS
  <Outputs if any, otherwise state None - example: Log file stored in C:\Windows\Temp\<name>.log>
.NOTES
  Version:        1.0
  Author:         <Name>
  Creation Date:  <Date>
  Purpose/Change: Initial script development
  
.EXAMPLE
  <Example goes here. Repeat this attribute for more than one example>
#>

#---------------------------------------------------------[Initialisations]--------------------------------------------------------

#Set Error Action to Silently Continue
$ErrorActionPreference = "SilentlyContinue"

#Dot Source required Function Libraries
. "C:\Scripts\Logging_Functions.ps1"

#----------------------------------------------------------[Declarations]----------------------------------------------------------

#Script Version
$sScriptVersion = "1.0"

#Log File Info
$sLogPath = "C:\Windows\Temp"
$sLogName = "Write_PA_PasswordPolicy.log"
$sLogFile = Join-Path -Path $sLogPath -ChildPath $sLogName

#-----------------------------------------------------------[Functions]------------------------------------------------------------
Import-Module ActiveDirectory

$OU1 = 'OU=OCIO_SecTest,OU=Priviledged_Access,OU=_Users,DC=test,DC=org'
$SecGroup = (Get-ADGroup -Identity 'PrivilegedUserPasswordPolicy').DistinguishedName

{
Get-ADUser –SearchBase $OU1 –LDAPFilter "(&(objectCategory=person)(objectClass=user)(!(memberOf=$SecGroup)))"  | {Add-ADPrincipalGroupMembership –MemberOf "$SecGroup"}
}



#-----------------------------------------------------------[Execution]------------------------------------------------------------

#Log-Start -LogPath $sLogPath -LogName $sLogName -ScriptVersion $sScriptVersion
#Script Execution goes here
#Log-Finish -LogPath $sLogFile

Open in new window

Subash SundharanIT Infrastructure Architect Commented:
There are some unwanted curly brackets and code details which I removed now, test and let me know if you have any questions..
#Set Error Action to Silently Continue
$ErrorActionPreference = "SilentlyContinue"

#Dot Source required Function Libraries
. "C:\Scripts\Logging_Functions.ps1"

#----------------------------------------------------------[Declarations]----------------------------------------------------------

#Script Version
$sScriptVersion = "1.0"

#Log File Info
$sLogPath = "C:\Windows\Temp"
$sLogName = "Write_PA_PasswordPolicy.log"
$sLogFile = Join-Path -Path $sLogPath -ChildPath $sLogName

#-----------------------------------------------------------[Functions]------------------------------------------------------------
Import-Module ActiveDirectory

$OU1 = 'OU=OCIO_SecTest,OU=Priviledged_Access,OU=_Users,DC=test,DC=org'
$SecGroup = (Get-ADGroup -Identity 'PrivilegedUserPasswordPolicy').DistinguishedName

Get-ADUser –SearchBase $OU1 –LDAPFilter "(&(objectCategory=person)(objectClass=user)(!(memberOf=$SecGroup)))"  | Add-ADPrincipalGroupMembership –MemberOf $SecGroup

#-----------------------------------------------------------[Execution]------------------------------------------------------------

#Log-Start -LogPath $sLogPath -LogName $sLogName -ScriptVersion $sScriptVersion
#Script Execution goes here
#Log-Finish -LogPath $sLogFile

Open in new window

Subash SundharanIT Infrastructure Architect Commented:
Added simple error logging.. Test it and see if it works for you..
#Set Error Action to Silently Continue
$ErrorActionPreference = "SilentlyContinue"
#Log File Info
$sLogPath = "C:\Windows\Temp"
$sLogName = "Write_PA_PasswordPolicy.log"
$sLogFile = Join-Path -Path $sLogPath -ChildPath $sLogName
$Error.Clear()

Import-Module ActiveDirectory

$OU1 = 'OU=OCIO_SecTest,OU=Priviledged_Access,OU=_Users,DC=test,DC=org'
$SecGroup = (Get-ADGroup -Identity 'PrivilegedUserPasswordPolicy').DistinguishedName

Get-ADUser –SearchBase $OU1 –LDAPFilter "(&(objectCategory=person)(objectClass=user)(!(memberOf=$SecGroup)))"  | Add-ADPrincipalGroupMembership –MemberOf $SecGroup
#Log Error
$Error | Out-file $sLogFile -Append

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Peter CopeAuthor Commented:
I dont know why i am getting this. I copied the exact same code from your previous post.

At C:\scripts\Write_PA_PasswordPolicy.ps1:14 char:151
+ ... upMembership –MemberOf $SecGroup
+                    ~~~~~~~~~~~~~~~~~~~
The string is missing the terminator: ".
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
Subash SundharanIT Infrastructure Architect Commented:
upMembership –MemberOf $SecGroup
Probably related to the encoding of the script file, is it saved in ANSI?

Open the script file in notepad and check the encoding.. You can use the save as option to change the encoding and save the file.
Peter CopeAuthor Commented:
Thank you so much for your help.
Peter CopeAuthor Commented:
I am looking to schedule this to run. What is the best way to go about that?
Peter CopeAuthor Commented:
Also as for the logging, I am looking to log when a user is added to the Security group. How would i do that?
Subash SundharanIT Infrastructure Architect Commented:
You can schedule it on any computer which had Activedirectory module.

Example, following command can be used to trigger a script, you may save this command as a batch (.bat) file and run it from task scheduler..
Powershell.exe -executionpolicy remotesigned -File  C:\Script\ADScript.ps1

Open in new window

Also there are many article available in internet which will help you to do the same.. Just search
how to schedule a powershell script in task scheduler
Subash SundharanIT Infrastructure Architect Commented:
Also as for the logging, I am looking to log when a user is added to the Security group. How would i do that?
This require additional error handling.. Please open new question for additional requests..
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.