Solved

PowerShell add users to group based on OU - Schedule script

Posted on 2016-10-14
14
52 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
Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

 

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

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

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

This article explains how to prepare an HTML email signature template file containing dynamic placeholders for users' Azure AD data. Furthermore, it explains how to use this file to remotely set up a department-wide email signature policy in Office …
A brief introduction to what I consider to be the best editor for PowerShell.
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

828 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