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

Viewing 2 reply threads
  • 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
      Participant
      Topics: 0
      Replies: 42
      Points: 404
      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

Viewing 2 reply threads
  • The topic ‘Getting AD users from group and then build a path with every samAccountName’ is closed to new replies.