powershell - Disabled ActiveDirectory Users from specific date with exclude list -
i wrote script gonna disabled old users... , need exclude list it... exclude list should .csv, 3 columns "name","samaccountname","reason"... i'm kind of stuck exclude list filtering... tried -notmatch , -notcontains , nothing worked me... try foreach if same...
function get-adlockoldusers { param () begin{ [datetime]$mydate = '01/01/1601 02:00:00' $colobj = @() $allusers = (get-aduser -filter * -properties lastlogontimestamp | ? {$_.enabled} | select-object name,samaccountname,@{n="lastlogon";e={[datetime]::fromfiletime($_.lastlogontimestamp)}}) $allusers = $allusers | ? {(get-date).adddays(-30) -gt $_.lastlogon -and -not ($_.lastlogon -eq $mydate)} } process { $allusers | % { $obj = new-object psobject $obj | add-member noteproperty 'name' $_.name -force $obj | add-member noteproperty 'samaccountname' $_.samaccountname -force $obj | add-member noteproperty 'lastlogon' $_.lastlogon -force $obj | add-member noteproperty 'needdisabled' $true -force $colobj += $obj } } end { return $colobj } } function set-adlockuser { param() begin{ if (test-path '.\excludeusers.csv') { $excludeusers = import-csv '.\excludeusers.csv' $duser = @() $colusers = get-adlockoldusers $colusers | ? {$_.samaccountname -notcontains $excludeusers} | % {set-aduser -identity $_.samaccountname -enabled $false -whatif } } else { write-output "error! excludeusers.csv cannot found, stop script"; break } } process { } end{} } set-adlockuser
a string value can never contain array, so
$_.samaccountname -notcontains $excludeusers
will evaluate $true
. need reverse check , make reference array of strings (the csv import produces array of custom objects). selecting field samaccountname
imported csv , switching arguments should want:
$excludeusers = import-csv '.\excludeusers.csv' | % { $_.samaccountname } ... $colusers | ? { $excludeusers -notcontains $_.samaccountname } | ...
as side note, simplify the code finding obsolete accounts this:
$mydate = get-date '01/01/1601 02:00:00' $limit = (get-date).adddays(-30) $colobj = get-aduser -filter * -properties * ` | ? { $_.enabled } ` | select name,samaccountname,@{n="needdisabled";e={$true}}, @{n="lastlogon";e={[datetime]::fromfiletime($_.lastlogontimestamp)}} ` | ? { $limit -gt $_.lastlogon -and $_.lastlogon -ne $mydate }
Comments
Post a Comment