Deploy gMSA account as task scheduler user account - powershell

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

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?

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?

PowerShell scheduled task: opens PowerShell and script to be run but doesn't execute script

$Trigger = New-ScheduledTaskTrigger -AtLogOn
$User = "Administrator"
$Action = New-ScheduledTask -Execute "PowerShell_ISE.exe" -Argument "C:\Payload\XML_Read.ps1"
Register-ScheduledTask -TaskName "StartupScript_PS" -Trigger $Trigger -User $User -Action $Action -RunLevel Highest -Force
This is my code which creates a scheduled task and runs fine upon logon. the problem is when it logs on it opens PowerShell and the XML_Read file but I have to manually click run for the XML file to be read etc. Is there a way I can modify my code to do this for me? thanks in anticipation.
You can't execute scripts automatically with the ISE. Instead of PowerShell_ISE.exe, use PowerShell.exe.

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.