how to filter an array to another array with powershell

Yonglong YL44 Wang 61 Reputation points
2021-12-17T09:29:50.973+00:00

there are multiple sub dir in d:\aaa , such as
D:\AAAA > dir
---- anitha1
---- yolanda
........................
----- ashok1

the dir name is also user id of a windows domain, my target is to remove the unvalid id (same as the dir name).

$userlist = Get-ChildItem -Path 'D:\AAAA' -Directory
$userlist.count
foreach ($d in $userlist)
{
$user_status= net user $d /domain |findstr "Account active" |findstr No |find /c /v ""
if ( [int]$user_status -gt 0 )
{
----------- how to put the invalid user list to another array named as $invalid_userlist
Move-Item $d D:\AAAA\will_be_deleted\
}
}

when i run it, it show :

FIND: Parameter format not correct
The user name could not be found.

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,462 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,906 Reputation points
    2021-12-21T15:58:25.01+00:00

    Use Move-Item inside the ForEach-Object loop.

    $invalid_userlist = @()
    (Get-ChildItem -Path 'D:\AAAA' -Dir) |
        ForEach-Object {
            $dir = $_.FullName
            $name = $_.Name
            Get-ADUser -Filter "samaccountname -eq '$($_.Name)' -and enabled -eq 'false'" |
                ForEach-Object {
                    $invalid_userlist += $_         # place the entire user object into the $invalid_userlist
                    Move-Item -Path $dir -Destination "D:\AAAA\will_be_deleted\$name"
                }
        }
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 45,906 Reputation points
    2021-12-17T20:20:33.087+00:00

    Something like this might be what you're looking for:

    $invalid_userlist = @()
    (Get-ChildItem -Path 'D:\AAAA' -Dir) |
        ForEach-Object{
            Get-ADUser -Filter "samaccountname -eq '$($_.Name)' -and enabled -eq 'false'" |
                ForEach-Object{
                    $invalid_userlist += $_         # place the entire user object into the $invalid_userlist
                }
            }