Powershell script not working through Task Scheduler

Pankajbhakta95 106 Reputation points
2021-04-15T01:35:54.57+00:00

Hi,
I am trying to disable few users on AD with the help of a simple PowerShell script as below.


Import-Module ActiveDirectory

Read content from DisableUser.csv file

$users=Import-CSV C:\ADUSERS\DisableUsers.csv

ForEach ($user in $users)
{
Disable-ADAccount -Identity $($user.name)

}


When I run the above script from my laptop through PowerShell console it works fine and disables the AD accounts but the script does not run
through the Task Scheduler. In the Scheduler I found that the Task starts and finishes but the script does not run.

I even added the command below to check it the script runs but no luck.

Set-Content -Path "C:\ADUSERS\TestTaskSch.txt" -Value "Hello World"

The Task Scheduler settings are given below.

Program/Script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Argument : -File "C:\PSScripts\DisableADUsers.ps1" ( file location of the script)

Kindly help.

Cheers

Pankaj

Windows 10
Windows 10
A Microsoft operating system that runs on personal computers and tablets.
12,074 questions
{count} votes

Accepted answer
  1. MotoX80 35,726 Reputation points
    2021-04-15T23:53:56.263+00:00

    Look in the History tab for errors.

    Change the task to run cmd.exe instead of powershell.exe. In the arguments field specify a bat file name, C:\PSScripts\DisableADUsers.bat

    Create the .bat file to call the PS script but also redirect stdout and stderr to a log file where you can check for error messages.

    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -File "C:\PSScripts\DisableADUsers.ps1"  1>C:\Windows\temp\DisableADUsers.log 2>&1 
    

1 additional answer

Sort by: Most helpful
  1. Karlie Weng 19,256 Reputation points Microsoft External Staff
    2021-04-15T08:28:50.587+00:00

    Hello @Pankajbhakta95

    1. First please check your configuration steps :How to: Run PowerShell Scripts from Task Scheduler
    2. Change that to "Run whether user is logged on or not".
    3. Leave the Do Not Store password option unchecked
    4. Mark "Run with Highest Privileges" option
    5. The account being use to execute task must have "Logon as batch job" rights under the local security policy of the server (or be member of local Admin group). You must specified the account you need to run scripts/bat files.

    Please see:
    Task Security Context

    Powershell script does not run via Scheduled Tasks

    Best Regards
    Karlie

    ----------

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer