Solved

PowerShell add users to group based on OU - Schedule script

Posted on 2016-10-14
14
39 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
  • 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
 

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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Hi all.   The other day I had to change the passwords for a bunch of users on the fly. Because they were so many, I decided to do it in an automated way and I would like to share it with you all.   If you are not doing it directly in a Domain Co…
A procedure for exporting installed hotfix details of remote computers using powershell
This video discusses moving either the default database or any database to a new volume.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

757 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now