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


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:



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?

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'}


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

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

Thank you very much

Worked like a charm