I'm trying to schedule a task in Windows 10, on the event of "At log on" in order to start several programs, but it won't run after several trial/error. The task is configured as follows:
General: Run whether user is logged on or not (it prompted the credentials inputbox, also tried Run only when user is logged on). Run with highest privilegies. Configure for Windows 7 and Windows 10 options where tried.
Triggers: At log on, any user, enabled (tried specific user too).
Actions: Start a program, which are "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", "C:\Program Files\Internet Explorer\iexplore.exe" (this one has Add Arguments: %HOMEDRIVE%%HOMEPATH%), "D:\ids\sqldeveloper\sqldeveloper\bin\sqldeveloper64W.exe". The route were copy/paste from the shortcut properties of each program.
Conditions: No condition were set.
Setting: No additional settings.
History: disabled.
When I restart and log on, nothing happens. Checking the status panel appears the summary of the task, where in the Last Run Time is 30/11/1999 12:00:00 a.m., the Last Run Result is (0x41303), and Status column is Ready.
Tried to look others questions, but seems to be others problems. What am I missing? Is there another configuration that I must apply? Thanks in advance.
I had this problem as well (Windows Server 2019), with error 0x41303 and Last Run Time set to 30/11/1999.
When I changed the start time to a future time instead of past (i.e. 2 minutes from current time), the scheduled task ran successfully (result: 0x0) and repeated just fine per the trigger.
Task Scheduler 0x41303: Task has not yet run.
The main reason for this is if the scheduler's first run is set in the past or simply hasn't run yet. To fix:
Try running it manually or
Set the next trigger in the near future.
The last run result should update indicating it ran but if it still doesn't run, check the task conditions.
A full list of task scheduler return codes
Try open "trigger" tab, and edit the trigger detail.
I found here my trigger was not enabled, I've just enabled it.
This could generate error 0x41303.
Got the same error code when scheduling a python script, fixed it by changing Conditions > Network to "Any connection" or disabling it entirely.
I had spaces in my script that was being called and had to change it to have quotes around it. Maybe this will help someone
Use "&&" in between the commands instead of commas and as far as possible try to give the absolute path to the arguments, hope this helps.
OR
You can create a ".bat" file with the different commands in it.
I think there's several possible reasons for this Last Run Result code. If you enable the task History and try running the scheduled task manually, you can check the History tab for events and should be able to get more information, such as an error code or error reason. Once you have that, you should be able to Google for the specific error message that you're getting.
In my case the run user (-User) was disabled and I constantly receive the code 267011 (0x41303). To check it run Get-LocalUser.
Setting the trigger start further into the future didn't seem to help. While not always going to be the right solution, running the task as SYSTEM got rid of 0x41303 for me.
$script = { "hello world" | write-host }
$registerJob = {
param($script)
$taskName = "Hello World"
Unregister-ScheduledJob -Name $taskName -ErrorAction Ignore
$job = Register-ScheduledJob -Name $taskName -ScriptBlock $([scriptblock]::create($script)) -RunEvery $([TimeSpan]::FromMinutes(1)) -MaxResultCount 1
$psSobsSchedulerPath = "\Microsoft\Windows\PowerShell\ScheduledJobs";
$principal = New-ScheduledTaskPrincipal -UserId SYSTEM -LogonType ServiceAccount
$someResult = Set-ScheduledTask -TaskPath $psSobsSchedulerPath -TaskName $taskName -Principal $principal
}
# Run as Administrator needed in order to call Register-ScheduledJob
powershell.exe -command $registerJob -args $togglePowerOverlay
On General Tab:
Choose "Run whether user is logged on or not"
Tick "Run with highest priviledge"
On Trigger Tab:
Make sure status is "Enabled"
In my case I launch task using another domain account but this account doesn't had rights for this. I added rights for launch task using this instruction.
Related
So there are several factors in play with this question, so here they are:
SailPoint 8.2 and IQService 8.2
Windows Server 2016
A service Account(Domain Admin)
An interactive User account (Domain admin)
Powershell 5.1 build 14393 revision 4583
So what we have is SailPoint is executing a rule on its end, sending over some information to IQService, and IQService is executing the PowerShell scripts as the service account. In one of the PowerShell scripts, we have the following command:
LogToFile("calling start job")
$j = Start-Job -ScriptBlock { C:/SailPoint/Scripts/PowershellContainerAfterCreateRetry.ps1 -sAMAccountName $args[0] -company $args[1] } -ArgumentList $sAMAccountName, $company -Name 'PowershellContainerAfterCreateRetry'
LogToFile($j | Select-Object -Property *)
LogToFile("finished start-job")
and this is where things get interesting because this command, as you can note, we can log to file to see what its output is, which is as follows:
calling start job
#{
State=Running; HasMoreData=True;
StatusMessage=;
Location=localhost;
Command= C:/SailPoint/Scripts/PowershellContainerAfterCreateRetry.ps1 -sAMAccountName $args[0] -company $args[1] ;
JobStateInfo=Running;
Finished=System.Threading.ManualResetEvent;
InstanceId=aa889c06-7a8a-402e-807a-880d02465bdd; Id=1;
Name=PowershellContainerAfterCreateRetry;
ChildJobs=System.Collections.Generic.List`1[System.Management.Automation.Job];
PSBeginTime=10/15/2021 21:14:22; PSEndTime=;
PSJobTypeName=BackgroundJob;
Output=System.Management.Automation.PSDataCollection`1[System.Management.Automation.PSObject];
Error=System.Management.Automation.PSDataCollection`1[System.Management.Automation.ErrorRecord];
Progress=System.Management.Automation.PSDataCollection`1[System.Management.Automation.ProgressRecord];
Verbose=System.Management.Automation.PSDataCollection`1[System.Management.Automation.VerboseRecord];
Debug=System.Management.Automation.PSDataCollection`1[System.Management.Automation.DebugRecord];
Warning=System.Management.Automation.PSDataCollection`1[System.Management.Automation.WarningRecord];
Information=System.Management.Automation.PSDataCollection`1[System.Management.Automation.InformationRecord]}
finished start-job
When I execute this command either by itself OR within this script using Windows PowerShell ISE, it completes with no issue and calls the script in question, and everything works perfectly! (whether I am using my interactive account OR the service account)
When this script executes using the IQService, something "else" is happening - I say something "else" because I don't have any log files or errors; it just seems to disappear into the ether. (I have a log write out five lines into the PowerShell script, so one would think I would at least get SOMETHING!?!? I am out of ideas...thoughts?
As a minor note, I ran an experiment that showed me that there is something strange about the setup which should have succeeded without issue - like the above it appears to execute (because I can see the same information above, that shows that the job has started). Still, just like the above, it never actually "appears" to complete or error out. The only thing I can think of is that somehow the primary script closing out is causing this to close out as well - but I would think it would be able to get a couple of log files written to if that was the case? Anyway...thanks for reading!
$doit = {
"test" | Out-File -filepath ("c:\test.txt") -append
}
Start-job -ScriptBlock $doit
i think Start-Job is the problem here, as iqservice will launch a powershell script process and that may not support the background job aspect you are trying to use.
if you need to have something retry or wait and loop, you'll need to use another identityiq/iqservice mechanism (a workflow in iiq perhaps that calls down to AD when conditions are, timer is hit, etc.) beyond start-job inside of an iqservice powershell script.
I was trying to test a simple powershell script with task scheduler, the status showed running but the powershell console never showed up.
My ps1 script just contains two simple commands:
dir
pause
Here is my setup:
General
Run whether user is logged on or not (check)
Run with highest privileges (check)
Actions
Action: Start a program
Program/Script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Add arguments (optional): -file E:\iQ_Schedule\Untitled1.ps1
This setup works on other computer (Windows 10) but just won't on this one (Windows Server 2012 R2). I am not sure why.
Welcome to Session 0 isolation mode.
When you run your task with "Run whether user logged in or not", it runs in so called session 0. You can check this with your task manager.
Tasks running is Session 0 has restrictions on showing the user interface
This could be due to the user account which is running the script. When the script is running with the SYSTEM account, the script will run in the background.
Try to change the option 'When running the task, use the following user account' to the account you are currently logged on with. Then the PowerShell console should pop up.
It sounds like the Windows Server 2012 R2 could have PSversion 2. The Pause function doesn't exist until PSversion 3.
Could you give the value of this command to us?
$PSVersionTable.PSVersion
Run whether user is logged on or not, will still give you the prompt. If the Hidden option is checked, you will not see the prompt.
I have also seen that the user that is trying to run the PowerShell script inside Task Scheduler doesn't have access to the folder strucutre. Make sure the user that is running the Task Scheduler has access to E:\iQ_Schedule\.
Make sure the user that is running the task scheduler has read access to the file structure you are trying to look up.
You can run as SYSTEM user, but then use the executionpolicy bypass argument
Powershell -ep Bypass 'e:\myPSFile.ps1' -myArg1 'arg1' -myArg2 'arg2'
I am using PowerShell for downloading data from email.
I want to run this process by PowerShell. When I run script like this:
D:\script.ps1
in powershell.exe it works fine.
When I schedule it in Task Scheduler nothing happens.
I tried it to Set it like Program/script:
powershell
Powershell.exe
powershell.exe
Add arguments:
-executionpolicy bypass -file D:\script.ps1
-file D:\script.ps1
-file "D:\script.ps1"
And nothing works. I'm using Windows 2008 R2.
Troubleshooting scheduled tasks is a pain in the rear, because you can't really see what's going on. These are some things you may want to check:
Check that your commandline works in principle, e.g. by running it from CMD (in your case try running powershell.exe -File "D:\script.ps1"). If that gives you any errors you need to fix those first.
If you intend to run the task as a particular user, start CMD as that user and run the same commandline to check if the user has all the permissions required for whatever the script is doing.
Check if your task actually terminated or if the process is still running (via Process Explorer, Get-Process, Task Manager, …).
Check the Last Run Result for the exit code of the command.
Enable the history for your scheduled tasks (Action → Enable All Tasks History). That will give you at least some information about what the task is doing, whether it starts at all, and if/which errors occurred. You need administrative rights to enable the task history.
Check the eventlog for errors/warnings correlating with the task run.
Add logging statements to the script you're running to record progress information. Personally I prefer logging to the eventlog, because that avoids filesystem permissions issues.
Write-EventLog -LogName Application -Source EventSystem -EventID 100 -EntryType Information -Message 'Your log message.'
If you have admin privileges on the system you can register an event source of your own and use that in the above log statement instead of abusing an existing source like EventSystem:
New-EventLog -Source MyEventSource -LogName Application
Further help will depend heavily on the findings you got following these steps as well as your actual script code.
I found this site that was quite useful:
http://www.microsoftpro.nl/2011/07/07/how-to-schedule-a-powershell-script-using-scheduled-tasks-in-windows-server-2008-r2/
I also changed Secure option property and it helped.
I didnt check: Do not store password and now it runs without me being logged into network.
Peace
Few major observations which I had faced:
Instead of giving only powershell.exe , try giving the full PS path C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe.
Permission is one more concern. The user through which you are running the task might not have the permission to run that.
Execution Policy: Make sure you are bypassing the execution policy using -ExecutionPolicy Bypass.
Make sure you are running the task with Highest Privileges.
Finally, through analysis of logs.
I need to run a powershell script whenever the server is rebooted/shutdown (whether graceful or disgraceful reboot).
The script will stop 4 application services at an interval of 1 minute and then finally reboots the system.(This is a business requirement, don't ask why)
How can I make server to invoke the .ps1 script whenever a reboot or a shutdown is initiated.
My test results:
I tried to create a test script which will generate a text file with current date/time and added it to the scheduled task on the trigger of event log 6006 (which is created whenever a system reboot/shutdown is initiated.)
I checked the box -"Run with highest privileges" but after system restart no text file was generated as it was supposed to, although it generates when ran manually.
Do we have any better approach to implement this?
(My final expectation should look like this-
On a random day a random user initiated reboot after a monthly patch when a command prompt window opens before him with message something like:
Stopping service abc...
Stopped.
Waiting for 60 seconds.
Stopping service xyz...
Stopped
EDIT: I've been successfully able to invoke the .ps1 file by adding it to the gpedit as suggested by Kory and Alroc but the script runs only in background when computer restart is initiated. It doesn't opens a regular cmd window to show the progress.
I'm adding the .ps1 script as well below which stops 2 services(chosen for testing purpose) at an interval of 10 seconds and will show the timer as well, only when ran manually.When invoked by the shutdown command it'll stop services only in the background without showing the progress to the user. Kindly assist to achieve this?
Write-Host "Shutdown script invoked"
stop-service W32Time -force -PassThru
for($i = 10 ; $i -gt 0 ; $i--)
{
Write-Progress -Activity "`n Waiting for" -status "`$i equals $i seconds"
sleep 1
}
stop-service wuauserv -force -PassThru
You can use GPO to configure a shutdown script for systems.
You might be able to to it via a Win32_ComputerShutdownEvent watcher as well.
After deep digging, I've finally figured out how to make the cmd window visible while system shutdown in progress.
Here is the complete steps of performing above mentioned expectation:
Open gpedit.msc
Navigate to Computer Configuration->Windows
Settings->Scripts(Startup/Shutdown)->Shutdown.
Go to Shutdown properties. In the powershell scripts tab add your
script and select 'Run Windows Powershell script first'
Above steps will enable the invoke of script at every system shutdown. Now to make the script visible and show progress:
Navigate to Computer Configuration->Administrative
Templates->System->Scripts
Among the policies showing in the right pane enable below
properties:
Run Windows Powershell scripts first at computer start,shutdown
Run shutdown scripts visible
I know this has been asked a 1000 times and I think I looked through all of them.
I have scheduled tasks running PowerShell Scripts on other servers already, but not on this server. Which has me scratching my head as to why I can't get it to work on this server.
I have a powershell script on a Windows 2008 R2 server. I can run it manually and it all works perfectly, but when I try to run it from a scheduled task the History says it was run, but the PowerShell script does not execute.
PSRemoting is enabled
The server ExecutionPolicy is "RemoteSigned"
I get two entries in the History
Action completed
Task Scheduler successfully completed task "\Processing" , instance "{dbbd4924-42d6-4024-a8ed-77494c7f84cf}" , action "C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.EXE" with return code 0.
Task complted
Task Scheduler successfully finished "{dbbd4924-42d6-4024-a8ed-77494c7f84cf}" instance of the "\Processing" task for user "domain\user".
The Scheduled Task looks like this:
I set to run under my account while I'm logged on. (since I can run the script manually as myself already)
checked Run with highest privileges.
trigger is to run every 10 minutes
Start a program Action.... Powershell.exe
Arguments: -executionpolicy remotesigned -File D:\abc\def\powershell\Processing.ps1
Conditions & Settings default settings.
Ensure that you're not being blocked by a permission issue with the task:
http://blogs.technet.com/b/askperf/archive/2012/04/18/task-scheduler-error-a-specified-logon-session-does-not-exist.aspx
The above GPO prevents credentials from being saved. Other User Rights Assignment settings can prevent things being run as batch/script/task/etc.
As a workaround, you can also set the task to run a .bat file with the powershell task. Adding an echo or pipe parameter may give you some clues to the issue.
I would recommend that you should add some diagnostic logging to this script to find out a place that causes this issue or redirect output of this script to a file. E.g. change your string with arguments this way:
-executionpolicy remotesigned -File D:\abc\def\powershell\Processing.ps1 2>&1 d:\output.log
Looks like that the script is executed, but something goes wrong. There are too many reasons for such behavior and it is difficult to find the root cause without a code.