Some PowerShell Assistance Please :) RRS feed

  • Question

  • Morning,

    I currently run a small/basic PowerShell script to copy users from an AD OU to a global security group for Microsoft Fine Grained Password Policies. This is working well, however, I have a new request that has come through and am struggling.

    I have looked through some forums with -FilterScript or -NotMatch used but have not been able to get this working.

    The current script runs through the OU recursively. This must not occur for this new script.

    There is a requirement for the script to run on parent OU(s) only, therefore ensure sub OU's are not read and users copied to the shadow group.

    ###What I would like to see is.

    $SourceOU can contain more that on 'distinguishedName'

    When running the command (or similar below) it will only 'Get' users from the predefined OU and not any OU members below.

    '(Get-ADUser -SearchBase $SourceOU -filter {userPrincipalName -like "*"}) | ForEach-Object {Add-ADGroupMember -Identity $ToAddGroupName -Members $_.SamAccountName}' 

    A log can be generated each time the script is run with members that have been added/removed from the Shadowgroup.

    Appreciate your help in advance.

    I have added an example of my script below.

    Can someone please help updating the script to fit my requirement?

    Import-module activedirectory
    $ToAddGroupName = "<myshadowgroup>"
    $SourceOU = "<my source OU>"
    (Get-ADUser -SearchBase $SourceOU -filter {userPrincipalName -like "*"}) | ForEach-Object {Add-ADGroupMember -Identity $ToAddGroupName -Members $_.SamAccountName}

    Thursday, August 8, 2019 9:26 AM

All replies

  • If I got you right you just need this:

    $ToAddGroupName = '<myshadowgroup>'
    $UserList = Get-ADUser -SearchBase $SourceOU -filter * -SearchScope OneLevel
    Add-ADGroupMember -Identity $ToAddGroupName -Members $UserList

    You don't need to import modules explicitly anymore since Powershell version 3.0. If you want to limit your AD query to the current OU you can use the parameter -SearchScope.

    BTW: Wehn you post code, please format it as code using the code posting tool provided on the icon bar of the post editor (second to last icon). Thanks

    Live long and prosper!


    • Edited by BOfH-666 Thursday, August 8, 2019 10:19 AM
    Thursday, August 8, 2019 10:18 AM