Environment: Server 2019 Domain Controller.
I have a simple script that combs through my AD users and disables anyone who hasn't logged in within the past 35 days (org policy). Looks like this:
Get-ADUser -Filter * -Properties Name,Lastlogontimestamp,PasswordNeverExpires | Where-Object {([datetime]::FromFileTime($_.lastlogontimestamp) -le (Get-Date).adddays(-35)) -and ($_.passwordNeverExpires -ne "true") } | Disable-ADAccount
If I run this manually, it works - blasts through the whole thing, finds anyone who hasn't been used in 35+ days and turns them off.
I originally tried to use Task Scheduler to call this script directly, but it didn't work - the task would "Run" forever but the script never executes because a user account I know that hasn't been used (which was one that got flagged in the manual run and I re-enabled to test the scheduled version) does not re-disable.
I tried modifying the script to have the execution policy turn off (and then back on at the end) but that didn't help either.
I did find this guidance that helped me a little bit: https://community.spiceworks.com/how_to/17736-run-powershell-scripts-from-task-scheduler
Instead of calling the script I call powershell and then pass it both the Set-ExecutionPolicy Bypass and the location of my script (which just sits on C:\ right now). This is a slight improvement because while the script still does not actually run (the barometer accounts don't disable again), the task does eventually stop and claim it ran successfully (0x1 code).
The credentials are correct for the domain admin account it runs as, and it is set to run with highest permissions (and if I'm logged in or not though I was logged in the whole time I was testing this).
I'm at a loss - every individual element appears to actually "work" - script totally functions, scheduler executes and "completes" - but the combined product does not.
Where am I going wrong? I have not had similar issues when using batch files so I suspect there's another element I am overlooking when it comes to doing this with PowerShell.