Process runs in Powershell Prompt but not as a scheduled task? - windows

$taskTrigger1 = New-ScheduledTaskTrigger -Once -At 2:50PM
$taskAction = New-ScheduledTaskAction `
-Execute "powershell.exe" `
-Argument "-ExecutionPolicy ByPass -File `"<path>\tiddlywikiIIS_schtask_rsync\backup.ps1`""
$taskName = "Backup Stuff"
$description = "Rsync Backup Stuff"
Register-ScheduledTask `
-TaskName $taskName `
-Action $taskAction `
-Trigger $taskTrigger1 `
-Description $description
$taskPrinciple = New-ScheduledTaskPrincipal -UserId "Domain\someadmin" -RunLevel Highest
$taskSettings = New-ScheduledTaskSettingsSet -Compatibility Win8
Set-ScheduledTask -TaskName $taskName -Principal $taskPrinciple -Settings $taskSettings
Set-ScheduledTask -TaskName $taskName -User $taskPrinciple.UserID -Password '******'
# Pull the creds for a user account that has WSL installed on it.
$cred = Get-StoredCredential -Target "some-non-admin-credz"
$psi = New-Object System.Diagnostics.ProcessStartInfo -Property #{
RedirectStandardError = $true
RedirectStandardOutput = $true
UseShellExecute = $False
UserName = $cred.GetNetworkCredential().Username
Domain = $cred.GetNetworkCredential().Domain
Password = $cred.Password
WorkingDirectory = "C:\windows\"
FileName = "wsl"
Arguments = "-d Ubuntu-18.04 -e rsync -av --delete /mnt/c/stuff/ /mnt/o/stuff_bk/"
WindowStyle = "Hidden"
}
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $psi
$p.WaitForExit()
$p.ExitCode
backup.ps1
I have the code above running in a scheduled task that is running with an (domain?) administrator account.
When it returns from the scheduled task it's $p.ExitCode is -1073741502 but if I run the same code in an administrative powershell prompt run as the same (domain?) administrative account it runs fine.
It makes me thing that it has something to do with the Local Security Policy as I remember there being some sort of "Allow Batch Execution" or "Delegate" or some such privilege in there that prevents any group or user not included from running something as a batch job.
I also found the following log in the Event Viewer:
Okay, so I found a log entry in the System Log with a Source of Application Popup, Event ID 26 which reads:
EventData -> Caption: `wsl.exe - Application Error`
EventData -> Message: `The application was unable to start correctly (0xc0000142). Click OK to close the application.`

Related

Cannot register scheduled task for creating system restore points using Powershell

I am trying to automate creation of system restore points using Powershell (v7.2.6). Following are the commands that I have run:
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument 'ExecutionPolicy Bypass -Command "Checkpoint-Computer -Description \"Auto Backup\" -RestorePointType \"MODIFY_SETTINGS\""'
$trigger = New-ScheduledTaskTrigger -Weekly -At 9am
$stsettings = New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -StartWhenAvailable
These work fine but when I run...
Register-ScheduledTask -TaskName "Auto System Backup" -RunLevel Highest -Action $action -Trigger $trigger -Settings $stsettings
...I get the an error message: Register-ScheduledTask: The parameter is incorrect.
Not sure which parameter is incorrect though. What am I doing wrong here?
The below command is wrong. There is no -Monthly parameter in New-ScheduledTaskTrigger. Also what you have specified does not make sense, Monthly 9am??
$trigger = New-ScheduledTaskTrigger -Monthly -At 9am

Register-ScheduledTask : Access is denied. (HRESULT 0x80070005)

I'm trying to create a new Windows Scheduler Task, which will run some sync job.
The things are:
I want to use a separated service account, not Administrator
I want to run a job not to get tied with service account's password change. In Windows Scheduler Task it is a "Do not store password" check button ("-LogonType S4U" option below)
Job should be created by Powershell as job creation should be automated
I'm running commands below under local Administrator and get an error:
PS C:\Temp> $TaskAction = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "<ARGUMENTS>"
PS C:\Temp> $TaskSettingsSet = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Hours 3) -MultipleInstances IgnoreNew -DontStopIfGoingOnBatteries
PS C:\Temp> $TaskTrigger = New-ScheduledTaskTrigger -RandomDelay (New-TimeSpan -Minutes 40) -Weekly -DaysOfWeek Saturday -At 7:30am
PS C:\Temp> $TaskPrincipal = New-ScheduledTaskPrincipal -UserId "<SERVICE_USER>" -LogonType S4U
PS C:\Temp> Register-ScheduledTask -Action $TaskAction -Description "<DESC>" -Settings $TaskSettingsSet -Principal $TaskPrincipal -TaskName "<TASK_NAME>" -TaskPath "\" -Trigger $TaskTrigger
Register-ScheduledTask : Access is denied.
At line:1 char:1
+ Register-ScheduledTask -Action $TaskAction -Description "<DESC>" ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (PS_ScheduledTask:Root/Microsoft/...S_ScheduledTask) [Register-ScheduledTask], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070005,Register-ScheduledTask
<SERVICE_USER> has been added to "Log on as a batch job" local policy.
Permissions for C:\Windows\Tasks or C:\Windows\System32\Tasks set with iCACLS does not help.
I've even added <SERVICE_USER> to local Administrators group - the same error.
If I do everything via GUI - it asks me <SERVICE_USER> credentials and works fine.
What permissions do I lack?
The thing was in user, running PS: if your need a "Do not store password" check button in your job, you need all the code above in PS console being ran under <SERVICE_USER> (you need to add <SERVICE_USER> to "Allow log on locally" local policy).
An Ansible example:
- name: Create and register sync task
win_shell: |
$TaskAction = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "<ARGUMENTS>"
$TaskSettingsSet = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Hours 3) -MultipleInstances IgnoreNew -DontStopIfGoingOnBatteries
$TaskTrigger = New-ScheduledTaskTrigger -RandomDelay (New-TimeSpan -Minutes 40) -Weekly -DaysOfWeek Saturday -At 7:30am
$TaskPrincipal = New-ScheduledTaskPrincipal -UserId "<SERVICE_USER>" -LogonType S4U
Register-ScheduledTask -Action $TaskAction -Description "<DESC>" -Settings $TaskSettingsSet -Principal $TaskPrincipal -TaskName "<TASK_NAME>" -TaskPath "\" -Trigger $TaskTrigger
vars:
ansible_become: yes
ansible_become_method: runas
ansible_become_user: <SERVICE_USER>
register: sync_task

Cannot process argument transformation on parameter 'Principal'. Cannot convert value "" to type "Microsoft.Management.Infrastructure.CimInstance"

I am trying to create a scheduled task in Powershell which will run a job that uses the active desktop.
1) is my assumption correct that a scheduled task can see the active desktop when it runs?
2) When I execute the following poweshell script, I keep getting an error: Cannot process argument transformation on parameter 'Principal'. Cannot convert value "Servername" to type "Microsoft.Management.Infrastructure.CimInstance"
The code is below:
import-module PSScheduledjob
$TaskStartTime = (Get-Date).AddMinutes(2)
$TaskName = "ExecTestCase"
write-output $TaskStartTime
$action = New-ScheduledTaskAction -Execute "C:\Selenium_Ruby\framework\run_locally_but_update_from_PROD_first.bat"
$trigger = New-ScheduledTaskTrigger -At $TaskStartTime -Once
$principal = "servername\userid" #assume servername \ userid is in quotes
Register-ScheduledTask BatchRunTask -action $action -principal $principal -trigger $trigger
What is wrong?
Also sometimes I get an access denied for the scheduled task too
thanks
The parameter -principal does not accept string input.
Refer to this documentation.
Example:
$STPrin = New-ScheduledTaskPrincipal -GroupId "BUILTIN\Administrators" -RunLevel Highest

Register-ScheduledJob as the system account (without having to pass in credentials)

I believe for Register-ScheduledTask you can specify -User "System"or do something like:
$principal = New-ScheduledTaskPrincipal -UserId SYSTEM -LogonType ServiceAccount -RunLevel Highest
How do I do this with Register-ScheduledJob?
This command will be running the context of the local admin so it will have access to do this. I just don't see this option in the cmdlet.
Here is an example of how to do this with the scheduled tasks cmdlet
edit: Does windows make this impossible by design? If I open an interactive PS session as the system (using psexec) and try to create a schedualed job I get an error:
PS C:\Windows\system32> Register-ScheduledJob -Name systemsssss -ScriptBlock {'s
dfsdfsdfsd'}
Register-ScheduledJob : An error occurred while registering scheduled job
definition systemsssss to the Windows Task Scheduler. The Task Scheduler
error is: (32,4):UserId:.
At line:1 char:1
+ Register-ScheduledJob -Name systemsssss -ScriptBlock {'sdfsdfsdfsd'}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Microsoft.Power...edJobDefini
tion:ScheduledJobDefinition) [Register-ScheduledJob], ScheduledJobExceptio
n
+ FullyQualifiedErrorId : CantRegisterScheduledJobDefinition,Microsoft.Pow
erShell.ScheduledJob.RegisterScheduledJobCommand
This same command works fine when run as the local administrator account
First use Register-ScheduledJob to create your PowerShell job.
Then use Set-ScheduledTask to change a startup account to the Local System or any other built-in accounts, i.e. SYSTEM, LOCAL SERVICE, NETWORK SERVICE, etc.
Use the following PS-script. Or download it from my GitHub Gist
The code is self-explanatory (I believe).
You can run it multiple times under an administrative account if you want to check how it works.
BTW, I prefer to use jobs (Register-ScheduledJob) over tasks because jobs allow me to embed PowerShell script blocks (strings) instead using of external script files. Look at -ScriptBlock below.
Also pay attention to -RunElevated. It is a must be.
$ErrorActionPreference = 'Stop'
Clear-Host
#### Start of Main Logic ###########################
$taskName = "my_PowerShell_job"
$accountId = "NT AUTHORITY\SYSTEM";
#$accountId = "NT AUTHORITY\LOCAL SERVICE";
$task = Get-ScheduledJob -Name $taskName -ErrorAction SilentlyContinue
if ($task -ne $null)
{
Unregister-ScheduledJob $task -Confirm:$false
Write-Host " # The old ""$taskName"" PowerShell job has been unregistered"; Write-Host;
}
# Uncomment the following exit command to only delete your job.
# exit;
# Shchedule your job. Using of -AtStartup as an example.
$trigger = New-JobTrigger -AtStartup;
$options = New-ScheduledJobOption -StartIfOnBattery -RunElevated;
Write-Host " # Registering of ""$taskName"" job";
Register-ScheduledJob -Name $taskName -Trigger $trigger -ScheduledJobOption $options `
-ScriptBlock {
# Put your code here.
Write-Host Your job has been launched!;
}
$principal = New-ScheduledTaskPrincipal -UserID $accountId `
-LogonType ServiceAccount -RunLevel Highest;
$psJobsPathInScheduler = "\Microsoft\Windows\PowerShell\ScheduledJobs";
$someResult = Set-ScheduledTask -TaskPath $psJobsPathInScheduler `
-TaskName $taskName -Principal $principal
#### End of Main Logic ###########################
Write-Host;
Write-Host " # Let's look at running account of ""$taskName"" PowerShell job"
$task = Get-ScheduledTask -TaskName $taskName
$task.Principal
Write-Host " # Let's start ""$taskName"" manually"
Start-Job -DefinitionName $taskName | Format-Table
Write-Host " # Let's proof that ""$taskName"" PowerShell job has been launched"; Write-Host;
Start-Sleep -Seconds 3
Receive-Job -Name $taskName
Write-Host;
Sadly you can't run schedule a job or task as the system account.
But you can create local administrator accounts as the system account.
And you can schedule jobs or tasks as a local administrator account.
So what I did to get around this problem is this:
$password = ConvertTo-SecureString (New-Guid).Guid -AsPlainText -Force
$user = New-LocalUser "service.scheduler" -Password $Password -Description "For scheduling in tasks from system account"
$credentials = New-Object System.Management.Automation.PSCredential($user.name, $password)
Register-ScheduledJob -Trigger $trigger -ScriptBlock $scriptblock -Name $taskName -ScheduledJobOption $options -credential $credentials
This does mean you are passing in credentials, but you don't have to store them as plain text or specify them.
Sorry, can't make comments with reputation under 50.
Can you use Group Policy to run it as a start up script? That will run as the Local System account. Doesn't look like this cmdlet has the -verb paramater to runas.
Looking at: https://technet.microsoft.com/en-us/library/hh849755.aspx under -ScheduledJobOption there is a setting in there RunElevated=$False, that is the defualt. If you set that to true does it run as admin?
I haven't tried it, it might work.
Hope this helps.
Thanks, Tim.

Powershell run job at startup with admin rights using ScheduledJob

To ease some of my work I have created a powershell script which needs to :
Run at startup.
Run with admin rights as it has to write in c:\program files folder.
I created the startup service using powershell like this :
function MakeStartupService
{
Write-Host "Adding script as a startup service"
$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:15
Try
{
Register-ScheduledJob -Trigger $trigger -FilePath "absolute_path" -Name "Job-name" -EA Stop
}
Catch [system.exception]
{
Write-Host "Looks like an existing startup service exists for the same. Overwriting existing job"
Unregister-ScheduledJob "Job-name"
Register-ScheduledJob -Trigger $trigger -FilePath "absolute_path" -Name "Job-name"
}
}
The job is registered as a startup service successfully and is visible inside task scheduler. If I start it using Start-Job -DefinitionName Job-name or by right clicking from Task Scheduler, it works fine but it doesn't start when windows starts.
Currently I am testing this on my personal Windows 10 system, and have checked in another windows 10 system but the behavior remained name. I am attaching screenshot of task scheduler window for this job.
Sorry if this questions sounds repeated or dumb (I am a beginner in powershell), but believe me, none of the solutions I found online worked for this.
Thanks in advance !!
This is code that is already in production that I use. If it does not work for you, you must have something else going on with your system.
function Invoke-PrepareScheduledTask
{
$taskName = "UCM_MSSQL"
$task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
if ($task -ne $null)
{
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false
}
# TODO: EDIT THIS STUFF AS NEEDED...
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-File "C:\Invoke-MYSCRIPT.ps1"'
$trigger = New-ScheduledTaskTrigger -AtStartup -RandomDelay 00:00:30
$settings = New-ScheduledTaskSettingsSet -Compatibility Win8
$principal = New-ScheduledTaskPrincipal -UserId SYSTEM -LogonType ServiceAccount -RunLevel Highest
$definition = New-ScheduledTask -Action $action -Principal $principal -Trigger $trigger -Settings $settings -Description "Run $($taskName) at startup"
Register-ScheduledTask -TaskName $taskName -InputObject $definition
$task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
# TODO: LOG AS NEEDED...
if ($task -ne $null)
{
Write-Output "Created scheduled task: '$($task.ToString())'."
}
else
{
Write-Output "Created scheduled task: FAILED."
}
}
If it works, it's not a script problem. Assign it to the SYSTEM account or make a separate service account instead of the Gagan account shown. Make sure that service account has "Permission to run as batch job" in your local security policy.
If you want to get rid of that "on battery" crap, add
-DontStopIfGoingOnBatteries -AllowStartIfOnBatteries
to New-ScheduledTaskSettingsSet options.
So, in Kory Gill answer, $settings becomes:
$settings = New-ScheduledTaskSettingsSet -Compatibility Win8 -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries
so task will be created to get rid of battery restrictions.
If you just want to modify an existing task, you can do it with:
Set-ScheduledTask -taskname "taskName" -settings $(New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries)
or from cmd:
powershell -executionpolicy bypass Set-ScheduledTask -taskname "taskName" -settings $(New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries)
Please check the checkbox for "Run with highest privileges" for the task in the task scheduler and try again. Currently in the screenshot above it is unchecked.
I have circled it below in red for your easy reference:

Resources