Improve company productivity with a Business Account.Sign Up

x
?
Solved

PowerShell add users to group based on OU - Schedule script

Posted on 2016-10-14
14
Medium Priority
?
92 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
13 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
Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

 

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 2000 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

Worried about phishing attacks?

90% of attacks start with a phish. It’s critical that IT admins and MSSPs have the right security in place to protect their end users from these phishing attacks. Check out our latest feature brief for tips and tricks to keep your employees off a hackers line!

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

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.
In migration, Powershell can be a very crucial tool to achieve success and finalize projects within deadline or even fix issues. X500 or Legacy Exchange DN Attribute can cause lots of issue during the migration
Screencast - Getting to Know the Pipeline
Did you know PowerShell can save you time with SaaS platforms? Simply leverage RESTfulAPIs to build your own PowerShell modules. These will kill repetitive tickets and tabs, using the command Invoke-RestMethod. Tune into this webinar to learn how…

608 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