Create scheduled task with power shell in a Remote Machine - powershell

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/

Related

Scheduled task created in Powershell runs but does not run Powershell script?

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?

PowerShell script as a task scheduler doesn't work correctly

When I run the task scheduler it gives me a (0x1) error code. Basically this is to copy all files on the desktop and place them in Google Drive.
Backup1.ps1
$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument 'C:\Users\User\Desktop\Backup2.ps1'
$trigger = New-ScheduledTaskTrigger -Daily -At 9am
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "BackUP Google Drive" -Description "Google Drive Backup"
Backup2.ps1
Copy-Item "C:\Users\User\Desktop\*" -Destination "G:\My Drive\BackUp" -Recurse -Force
The Backup2.ps1 works 100% of the time when running it under PowerShell alone. The problem is that the task scheduler isn't completing the task due to the (0x1) error.

Unable to create 2 machine environment variables and execute another command via a Scheduled Task

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

Can you delete a windows task with another task trough powershell?

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?

Run ScheduledTask on first day of month?

I am trying to run a batch file from powershell, the script should run every 1 of the month.
But what this does is, it runs the batch file regardless of the time given.
I'm totally new to powershell so can't figure it out.
$trigger= New-ScheduledTaskTrigger -At 04:26pm –Daily # Specify the trigger settings
$action = Start-Process -FilePath C:\Users\xxx\abc.bat -Wait -passthru;$a.ExitCode
Register-ScheduledTask -Action $action -Trigger $trigger
this example is from https://www.verboon.info/2013/12/powershell-creating-scheduled-tasks-with-powershell-version-3/
the action is not Start-Process but New-ScheduledTaskAction
$TaskAction = New-ScheduledTaskAction -Execute "$TaskCommand" -Argument "$TaskArg"
$TaskTrigger = New-ScheduledTaskTrigger -At $TaskStartTime -Once
Register-ScheduledTask -Action $TaskAction -Trigger $Tasktrigger -TaskName "$TaskName" -User "System" -RunLevel Highest
There is a great answer here it shows you how to create a job to run daily, weekly or monthly in Powershell. Running monthly is a little more difficult as Powershell doesn't have a parameter option for monthly.