When using following powershell script which creates a scheduled task to delete another scheduled task, I am confronted with an error (access denied: 0x80070005). When I manually define the task and execute it, it works fine.
# Prep task 2 for taskscheduler > delete task 1 after reboot if not deleted before
$Action2 = New-ScheduledTaskAction -Execute "C:\Windows\system32\cmd.exe" -Argument "/c schtasks /delete /tn 'Computer Forced Reboot'/f"
$Trigger2 = New-ScheduledTaskTrigger -AtLogon
$Settings2 = New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -Compatibility Win8 -RestartCount:10 -RestartInterval (New-TimeSpan -Minutes 1)
$Principal2 = New-ScheduledTaskPrincipal -UserID "domain\$env:UserName" -LogonType Interactive
# Register task 2 to Taskscheduler
Register-ScheduledTask -TaskName "test test" -Action $Action2 -Trigger $Trigger2 -Settings $Settings2 -Principal $Principal2here
What am I doing wrong? Is this not possible (specific rights) trough powershell? Is there a workaround?
Related
I have a PS script that runs just fine when run manually, but I am trying to set it to run daily and can't seem to figure out why it won't run. The scheduled task itself will start, but the script doesn't actually seem to run. Any help would be appreciated.
This is what I used to create the scheduled task:
$Trigger= New-ScheduledTaskTrigger -At 11:00am –Daily
$User= "NT AUTHORITY\SYSTEM"
$Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-NoProfile -ExecutionPolicy Bypass -File G:\Path\ScriptName.ps1"
Register-ScheduledTask -TaskName "TaskyTask" -Trigger $Trigger -User $User -Action $Action -RunLevel Highest –Force
I created a script on my machine # C:\test\ScriptName.ps1
The script is:
Write-Output "HelloWorld" | Out-File C:\test\HelloWorld.txt
So I can verfiy it's success by seeing if HelloWorld.txt has been created in C:\Test
With a tweak to your code to account for the differnce in my script location:
$Trigger= New-ScheduledTaskTrigger -At 11:00am –Daily
$User= "NT AUTHORITY\SYSTEM"
$Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-NoProfile -ExecutionPolicy Bypass -File C:\Test\ScriptName.ps1"
Register-ScheduledTask -TaskName "TaskyTask" -Trigger $Trigger -User $User -Action $Action -RunLevel Highest –Force
The task appears in task scheduler, I run it and HelloWorld.txt is created, confirming it works. This to me suggests your script is executing, but maybe not doing what you think.
If you change your script to the same simple script above, does it run?
I would like to create 2 "machine" environment variables and also execute a command via a single Scheduled Task. The scheduled task should immediately run and delete itself. The scheduled task should be executing as the current logged-in desktop user.
Below are the 3 items I need to execute:
[Environment]::SetEnvironmentVariable('AppA', (Get-StartApps -Name 'PowerShell (Tools1)').AppID, 'Machine')
[Environment]::SetEnvironmentVariable('AppB', (Get-StartApps -Name 'PowerShell (Tools2)').AppID, 'Machine')
Export-StartLayout -path 'C:\temp\Orig.xml'
Note: I do NOT want to depend on an external script; which is why I have such a long line of code for $action
When I run the code below, almost always, none of the commands are executed. Very rarely, a single environment variable get's created. If it's impossible to do this reliably in a single task, I'm hoping someone could show me how to do this reliably in 3 separate tasks. It seems even if I do 3 separate tasks, the results are still inconsistent/unreliable.
Code:
$AppA = (Get-StartApps -Name 'Windows PowerShell ISE (x86)').AppID
$AppB = (Get-StartApps -Name 'Outlook').AppID
$action = New-ScheduledTaskAction -Execute "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-noprofile -windowstyle hidden -command ( [Environment]::SetEnvironmentVariable('AppA', $AppA, 'Machine') ; [Environment]::SetEnvironmentVariable('AppB', $AppB, 'Machine') ; Export-StartLayout -path 'C:\temp\Orig.xml' )"
$trigger = New-ScheduledTaskTrigger -Once -At (get-date).AddSeconds(4); $trigger.EndBoundary = (get-date).AddSeconds(8).ToString('s')
$principal = New-ScheduledTaskPrincipal -UserId (Get-WmiObject -Class win32_computersystem).UserName -LogonType ServiceAccount -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -DeleteExpiredTaskAfter 00:00:12
Register-ScheduledTask -TaskName "2 envvars and Export-StartLayout" -Action $action -Trigger $trigger -Principal $principal -Settings $settings
I am trying to create a task on windows 2016 server, and need to deploy gMSA account as the log on account and below is the script i am using, i need to ensure that the option- "Run whether user is logged or not" gets selected,what change should be made to below code?
$action = New-ScheduledTaskAction -Execute "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "NoProfile -ExecutionPolicy Unrestricted C:\Admin\Scripts\test.ps1 "
$trigger = New-ScheduledTaskTrigger -daily -At 5:05am
$Pri = New-ScheduledTaskPrincipal -UserId "Domain\gMSA" -LogonType ServiceAccount -RunLevel Highest
$task = New-ScheduledTask -Action $action -Trigger $trigger
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Taskname" -Principal $Pric
This is a similar request as the SO topic and answers / accepted answer.
Set a Scheduled Task to run when user isn't logged in
But since you are using a gMSA, you'd never know what that password is.
So, you can create the task normally and then do say this...
schtasks /change /TN \YourTaskName /RU DOMAIN\gMSA_Name$ /RP
Or in pure PowerShell, you again set the Scheduled Task and then do this...
New-ScheduledTaskPrincipal -UserID Domain\GMServiceAccount$ -LogonType Password
See the details of the above here:
Active Directory - Scheduled Tasks Using a gMSA
How can one create a task in task scheduler on a remote machine using Power shell?
To create a task in the scheduler you can use the New-ScheduledTaskAction, New-ScheduledTaskTrigger and Register-ScheduledTask cmdlets - detailed info can be found here: https://blogs.technet.microsoft.com/heyscriptingguy/2015/01/13/use-powershell-to-create-scheduled-tasks/
Here's an example:
$action = New-ScheduledTaskAction -Execute 'Powershell.exe' `
-Argument '-NoProfile -WindowStyle Hidden -command "& {get-eventlog -logname Application -After ((get-date).AddDays(-1)) | Export-Csv -Path c:\fso\applog.csv -Force -NoTypeInformation}"'
$trigger = New-ScheduledTaskTrigger -Daily -At 9am
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "AppLog" -Description "Daily dump of Applog"
Running Powershell remotely requires a few configuration changes, which you can find out about here: https://www.howtogeek.com/117192/how-to-run-powershell-commands-on-remote-computers/
I'm currently attempting to create a Powershell script that the overall goal will create a scheduled task on my VM which will reboot remote computers at certain times. The issue I'm currently having is trying to set the task to expire, and delete once it has been completed.
One point of confusion is there seems to be a disparity between the type of variable the cmdlet wants, and how an existing one is shown in the system. So as an example I have a dummy task that:
-Runs once at 11:00PM on 3/16/2017 and expires at 11:30PM on 3/16/2017 in the Triggers tab
-Has the setting "If the task is not scheduled to run again, delete it after: Immediately" under settings.
If I look at the existing task using Get-ScheduledTask this is what the values come across as:
(Get-ScheduledTask -TaskName Test).Settings
If I do a Get-Member these values are strings
(Get-ScheduledTask -TaskName Test).Settings | Get-Member
Now part of my issue may entirely be that I'm using the wrong cmdlets to go about this (just started messing around with this yesterday).The basic script I'm using while testing this out is:
function Create-Task ($Computer,$Time)
{
$Task = New-ScheduledTaskAction -Execute 'cmd.exe'`
-Argument "/c `"Shutdown /m \\$Computer /r /t 0`""
$Trigger = New-ScheduledTaskTrigger -Once -At $Time
$Settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit 'PT72H' -DeleteExpiredTaskAfter 'PT0S'
Register-ScheduledTask -Action $Task -Trigger $Trigger -TaskName "Test" -Description "Testing this out" -Settings $Settings
}
$Comp = "WIN7-0031B"
[datetime]$TriggerTime = '3/16/2017 11:00PM'
Create-Task -Computer $Comp -Time $TriggerTime
When I look at Get-Member for New-ScheduledTaskSettingsSet cmdlet it again says those values are strings
However, if I attempt to run the script as is it complains about them not being datetime variables:
"New-ScheduledTaskSettingsSet : Cannot process argument transformation on parameter 'ExecutionTimeLimit'. Cannot convert value "PT72H" to type "System.TimeSpan". Error: "String was not recognized as a valid TimeSpan.""
(I would post a screenshot but I just joined StackOverflow so don't have the reputation).
What I've so far attempted has been changing the $Settings variable to things such as:
$Settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 30).Minutes -DeleteExpiredTaskAfter (New-TimeSpan -Seconds 0).Seconds
and
$Settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 30).Minutes.ToString() -DeleteExpiredTaskAfter (New-TimeSpan -Seconds 0).Seconds.ToString()
In both scenarios it does not generate any error messages, but the setting just doesn't get created. I'm wondering if doing something like this requires creating the task without the setting, and then doing something like a
Get-ScheduledTask -TaskName 'Test' | Set-ScheduledTask <Some other code here>
type of method, but wasn't 100% sure about how to do this. I'm somewhat new to powershell and completely new to trying to create scheduled tasks through Powershell, and any help would be greatly appreciated! The version of Powershell is Version 5
Edit Comment: It looks like when I pasted my script to StackOverflow it is showing most of it as being within quotations and not sure why, but in my ISE it shows things properly.
Eventually was able to get this working. I found an additional StackOverflow post and an article that helped get me in the right direction:
Powershell v4. Create remote task scheduler task set to expire and delete
https://blogs.technet.microsoft.com/platformspfe/2015/10/26/configuring-advanced-scheduled-task-parameters-using-powershell/
The working script (at least as far as getting this specific aspect working) is:
function Create-Task ($Computer,$Time)
{
$ActionArgs = "/c `"Shutdown /m \\$Computer /r /t 0`""
$TaskAction = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument $ActionArgs
$TaskUserName = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount
$TaskSettings = New-ScheduledTaskSettingsSet -Compatibility V1 -ExecutionTimeLimit (New-TimeSpan -Minutes 30) -DeleteExpiredTaskAfter (New-TimeSpan -Seconds 0)
$TaskTrigger = New-ScheduledTaskTrigger -Once -At $Time
$Task = New-ScheduledTask -Action $TaskAction -Trigger $TaskTrigger -Principal $TaskUserName -Settings $TaskSettings
Register-ScheduledTask -TaskName "Test" -InputObject $Task -Force
$RegisteredTask = Get-ScheduledTask -TaskName "Test"
$RegisteredTask.Triggers[0].EndBoundary = $Time.AddMinutes(30).ToString('s')
$RegisteredTask.Settings.DeleteExpiredTaskAfter = 'PT0S'
$RegisteredTask | Set-ScheduledTask -User "NT AUTHORITY\SYSTEM"
}
$Comp = "WIN7-0031B"
[datetime]$TriggerTime = '3/17/2017 11:00PM'
Create-Task -Computer $Comp -Time $TriggerTime
One thing I also noticed I was doing wrong from the onset is I was confusing ExecutionTimeLimit with the EndBoundary property.
Also for reference, if you try running this in ISE without running ISE as admin you will most likely get an Access Denied issue. I'm planning to basically have this script as a scheduled task that looks for a CSV file to create the other tasks and will be running it as system so it shouldn't be a problem. But just in case someone happens across this thread and runs into the issue