Reputation: 981
I created a script file and I want this script to run at the time I set every day
I have used the following code for this operation but it does not work.
$app = New-ScheduledTaskAction -Execute "C:\Users\XXX\Desktop\script.ps1";
$time = New-ScheduledTaskTrigger -Daily -At 22:58pm
Register-ScheduledTask TEST1 -Action $app -Trigger $time;
How do I run script.ps1 at a specific time every day? Where did I make a mistake? How can I solve my problem?
NOTE: my powershell version
PSVersion 5.1.17134.407
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.17134.407
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
Upvotes: 0
Views: 14780
Reputation: 17345
There could be multiple issues. With the script itself, you did not provide the source. There could be also issue with the rights (do you have rights to create a task? Do you have rights to run the script from the destination?)
Anyways, from what you have posted the issue is that you are trying to run the script directly but you should --execute powershell.exe
first and then run the script.
This is one way to have your powershell script scheduled (note that it is running with the highest possible priviliges):
$TaskName = 'MyScript'
$User= "domain\user"
$ScriptPath = "C:\Users\XXX\Desktop\script.ps1"
$Trigger= New-ScheduledTaskTrigger -At 22:58 -Daily
$Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-executionpolicy bypass -noprofile -file $ScriptPath"
Register-ScheduledTask -TaskName $TaskName -Trigger $Trigger -User $User -Action $Action -RunLevel Highest -Force
Upvotes: 3