-1

I have a large folder E:\Users that has a folder for each user by their logon name for example E:\Users\jt10192.

I want to loop through every folder in E:\Users and get a list of home folders that belonged to users that have since been deleted.

This is how far I've got, but I'm not sure what to run to lookup if $folder is a user and output something if not.

$folders = Get-ChildItem | Where-Object { $_.PSIsContainer } | Select-Object Name

foreach ($folder in $folders) {

       // lookup if $folder is a user and output something if not...

}
sodawillow
  • 12,497
  • 4
  • 34
  • 44
Jack
  • 29
  • 6
  • 4
    You need to provide more information about your environment - for instance, is this an ActiveDirectory domain? What is your level of privilege? What research have you done toward solving this problem on your own, and what problems have you encountered in trying to use what you've found? – Jeff Zeitlin Jun 19 '17 at 12:18
  • @JeffZeitlin Apologies. I have updated the tags. Yes it's Active Directory and I am a Domain Admin. – Jack Jun 19 '17 at 15:52

1 Answers1

2

If you're using AD to lookup your users accounts:

$path = "E:\Users"
$folders = Get-ChildItem $path -Directory

ForEach ($folder in $folders) {
    If(Get-ADUser -Filter {sAMAccountName -eq $($folder.name)}){
        Write-Host "Found matching User for: $($folder.FullName)" -ForegroundColor Green
    }
    else {
        Write-Host "No account found for folder: $($folder.FullName)" -ForegroundColor Red
    }
}
henrycarteruk
  • 12,708
  • 2
  • 36
  • 40
  • 2
    `Get-ADUser` will throw an error if user does not exist and the `else` block will not be executed. Because of this I often use `Get-ADUser -Filter { SamAccountName -eq "JohnDoe" }` (or a `try/catch` construct. – sodawillow Jun 19 '17 at 14:06
  • @sodawillow So change `Get-ADUser $($folder.name)` to `Get-ADUser -Filter { SamAccountName -eq "$($folder.name)" }`? – Jack Jun 19 '17 at 15:53
  • 1
    Checked my script and I had actually used dsquery, but sticking with Get-ADUser and using the Filter is nicer. Answer updated accordingly. – henrycarteruk Jun 19 '17 at 16:07
  • [Some tips about this method](https://stackoverflow.com/questions/20075502/get-aduser-filter-will-not-accept-a-variable) – sodawillow Jun 19 '17 at 16:37
  • This results in `Get-ADUser : Cannot process argument because the value of argument "path" is not valid. Change the value of the "path" argument and run the operation again.`. – Jack Jun 19 '17 at 17:48
  • I changed it to `If(Get-ADUser -Filter "sAMAccountName -eq ""$($folder.name)"""){` and it works now. Accepting. Thanks. – Jack Jun 19 '17 at 17:54