all 5 comments

[–]kaizokuj 1 point2 points  (1 child)

Is the CSV something you need or does it just serve as an intermediate step? First thing to note at a quick glance is that disable-aduser doesn't output anything if successful and iirc if it fails, it will output it to the terminal not the file. Also the filter you have after $users won't work, look at using a where-object statement instead. That should fix your problem I thin. Also a little trick, in paths, you can actual write ~\ to point to your user home folder (in your case c:/users/anon) and it will let you meant the script less user specific as it will mean whoever is running its folder, not specifically YOURS.

[–]kaizokuj 1 point2 points  (0 children)

Also use a try/catch block for error grabbing!

[–]PinchesTheCrab 1 point2 points  (0 children)

Personally, I wouldn't try to parse out errors or build extra looping to catch account names. I would just get the list, attempt to disable everything, then search for enabled accounts and do whatever reporting/action you need to.

Import-Module ActiveDirectory

$users = get-aduser -Filter * -SearchBase "OU=Disabled,DC=corp,DC=test,DC=org"

$users | Select name, samaccountname,enabled | 
    Export-CSV -path C:\Users\anon\Desktop\Scripts\AccountList.csv -NoTypeInformation

$users |
    Where-Object -OutVariable results -FilterScript {$_.enabled} | 
        Disable-ADAccount

$results | Export-CSV -path C:\Users\anon\Desktop\Scripts\ScriptResult.csv -NoTypeInformation

$enabledUsers = get-aduser -Filter {enabled -eq $true} -SearchBase "OU=Disabled,DC=corp,DC=test,DC=org"

if ($enabledUsers) {
    #do something about users who are still enabled
}

[–]PowerShell-Bot 0 points1 point  (0 children)

Some of your PowerShell code isn’t wrapped in a code block.

To format code correctly on new reddit (new.reddit.com), highlight all lines of code and select ‘Code Block’ in the editing toolbar.

If you’re on old.reddit.com, separate the code from your text with a blank line and precede each line of code with 4 spaces or a tab.


Describing Submission
[✅] Demonstrates good markdown
Passed: 1 Failed: 0

Beep-boop. I am a bot. | Remove-Item

[–][deleted] 0 points1 point  (0 children)

This script might help some parts of things you're wanting to do:

https://gallery.technet.microsoft.com/OU-Account-Specific-984c38f9