Thursday, February 3, 2011

Get user home directories recursively in PowerShell

So, I'm taking the dive into PowerShell. I've been tasked with redoing permissions on every home folder in the domain (they do not all fall under the same sub-directory - that would be too easy). I have a batch script written that takes two parameters: user name, and home folder path and pumps them through SetACL.

I want to use PowerShell to get the user names and home folders for every user in an OU. So far, I can get the user names, but I cannot figure out how to get the home directories.

This is my PowerShell so far (borrowed from various sources across the web):

$Dom = "LDAP://OU=Accounts,DC=myDomain,DC=local"
$Root = New-Object DirectoryServices.DirectoryEntry $Dom

# Create a selector and start searching from the Root of AD
$selector = New-Object DirectoryServices.DirectorySearcher
$selector.SearchRoot = $root
$Selector.pagesize = 20000


# Basically this will only grab user accounts and not computer accounts.
$adobj= $selector.findall() | where {
    $_.properties.objectcategory -match "CN=Person*"
}
foreach ($person in $adobj) {
    $prop=$person.properties
    Write-host "$($prop.cn)"
}

I'm eventually going to pipe the Write-host line into the setACL batch file, but I'm just writing the output for now to make sure that it's accurate. I've tried adding$($prop.homeDirectory) to the Write-host line with no luck.

Any pointers or suggestions?

  • Use Quest's AD cmdlets, they're free and really simplify this sort of thing.

    You can get them from http://www.quest.com/powershell/activeroles-server.aspx

    Once you have those loaded, try the following script but also have a read around the Get-QADUser cmdlet.

    $csvfile = "C:\somefile.csv"
    $root = "OU=Accounts,DC=myDomain,DC=local"
    get-qaduser -SearchRoot $root `
    -ObjectAttributes @{homeDirectory=’*'} -IncludeAllProperties | `
    Select-Object LogonName,HomeDirectory | `
    Export-Csv $csvfile
    
    MarkM : +1, this seems to be working well. I'm going to run it against the 20k object OU that I want with the -SizeLimit set to 0 and see what I get. I'd still like to know what I was doing wrong above though, any idea?
    Shay Levy : No need to use -IncludeAllProperties, HomeDirectory is returned in the default output of Get-QADUser. You also need to specify '-SizeLimit 0' to be able to bypass the default 1000 objects limitation. Get-QADUser -SizeLimit 0 -SearchRoot "OU=Accounts,DC=myDomain,DC=local" -HomeDirectory * | Select-Object LogonName,HomeDirectory | Export-Csv C:\somefile.csv Mark, add these lines to your script: $selector.Filter = "(&(objectclass=user)(objectcategory=person)(HomeDirectory=*))" $selector.findall() | foreach {$_.properties.homedirectory)
    From

0 comments:

Post a Comment