Getting AD users from group and then build a path with every samAccountName

Welcome Forums General PowerShell Q&A Getting AD users from group and then build a path with every samAccountName

This topic contains 2 replies, has 2 voices, and was last updated by

 
Participant
1 month, 1 week ago.

  • Author
    Posts
  • #170842

    Participant
    Topics: 1
    Replies: 1
    Points: 13
    Rank: Member

    Hello

    My goal here is to build script that deletes files in a folder in a users homedirectory

    First I enumerate the users in an AD group and putting that in a variable.

    $Userlist = Get-ADGroupMember -identity "Groupname" | select samAccountName

    With that variable I run a ForEach and get a list of every users file in that particaular path

    ForEach($samAccountName in $Userlist)
    {
    $userpath = "UNC-path"+$samAccountName

    Get-ChildItem $userpath -Recurse
    }

     

    The problem here is that the resulting path is wrong when I do a wrtie-host in the Foreach to see what happens

    It looks like this:

    \\UNC-path\@{samAccountName=username}

     

    Why do I get  the @{samaccountname= in the path?

    I tried a few different approaches but either get the above result or a path missing the username entirely.

     

    Any ideas on what I'm doing wrong?

  • #170860

    Moderator
    Topics: 0
    Replies: 36
    Points: 331
    Team MemberHelping Hand
    Rank: Contributor

    The result of selecting a single property is an object with one property – if you output that, you'll see something like

    PS > [PSCustomObject]@{SamAccountName='jpruskin'}
    
    SamAccountName
    --------------
    jpruskin
    
    # If instead you expand the property, you will get the value within the property
    PS > [PSCustomObject]@{SamAccountName='jpruskin'} | Select-Object -ExpandProperty samaccountname
    jpruskin
    

    You probably either want to reference the content of that property, or use -ExpandProperty to end up with just the strings in SamAccountName.

    # So, either:
    $Userlist = Get-ADGroupMember -identity "Groupname" | Select samAccountName
    
    ForEach($samAccountName in $Userlist) {
        $userpath = "UNC-path"+$samAccountName.SamAccountName
    
        Get-ChildItem $userpath -Recurse
    }
    
    # Or...
    $Userlist = Get-ADGroupMember -Identity "Groupname" | Select-Object -ExpandProperty samAccountName
    
    ForEach ($samAccountName in $Userlist) {
        $userpath = "UNC-path"+$samAccountName
        Get-ChildItem $userpath -Recurse
    }
  • #170875

    Participant
    Topics: 1
    Replies: 1
    Points: 13
    Rank: Member

    Thank you very much

    Worked like a charm

You must be logged in to reply to this topic.