Solved

PowerShell add users to group based on OU - Schedule script

Posted on 2016-10-14
14
65 Views
Last Modified: 2016-11-02
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"}
0
Comment
Question by:Peter Cope
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 6
14 Comments
 
LVL 40

Expert Comment

by:Subsun
ID: 41844033
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..
0
 

Author Comment

by:Peter Cope
ID: 41870389
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
0
 
LVL 40

Expert Comment

by:Subsun
ID: 41870447
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..
0
[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

 

Author Comment

by:Peter Cope
ID: 41870528
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

0
 
LVL 40

Expert Comment

by:Subsun
ID: 41870606
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

0
 
LVL 40

Accepted Solution

by:
Subsun earned 500 total points
ID: 41870619
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

0
 

Author Comment

by:Peter Cope
ID: 41870652
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
0
 
LVL 40

Expert Comment

by:Subsun
ID: 41870666
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.
0
 

Author Comment

by:Peter Cope
ID: 41870710
Thank you so much for your help.
0
 

Author Comment

by:Peter Cope
ID: 41870714
I am looking to schedule this to run. What is the best way to go about that?
0
 

Author Comment

by:Peter Cope
ID: 41870718
Also as for the logging, I am looking to log when a user is added to the Security group. How would i do that?
0
 
LVL 40

Expert Comment

by:Subsun
ID: 41870725
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
0
 
LVL 40

Expert Comment

by:Subsun
ID: 41870726
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..
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Synchronize a new Active Directory domain with an existing Office 365 tenant
There are times when we need to generate a report on the inbox rules, where users have set up forwarding externally in their mailbox. In this article, I will be sharing a script I wrote to generate the report in CSV format.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…

635 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question