I have a script which launches an app on the VM and logs some data for the app. As Powershell script does not allow me to run the app in foreground I decided to schedule a task after 2 mins and then keep polling for the task completion.
I was using this command to register my task
$password= "password" | ConvertTo-SecureString -asPlainText -Force;
$username = "name";
$credential = New-Object System.Management.Automation.PSCredential($username,$password);
Invoke-Command -VMName INSTANCE_ID -Credential $credential -ScriptBlock
{
$gettime = (Get-Date).AddMinutes(2);
$run = $gettime.ToString('HH:mm');
$action = New-ScheduledTaskAction -Execute 'C:\logging.bat';
$trigger = New-ScheduledTaskTrigger -Once -At $run;
$principal = New-ScheduledTaskPrincipal -GroupID "BUILTIN\Administrators" -RunLevel Highest;
Register-ScheduledTask -Action $action -Trigger $trigger -Principal $principal -TaskName "ID_Logging_Task" -Description "my description"
}
It was working fine but it had a problem that it ran well only when the user was logged in. More context -
If you do this, this takes care of starting the VM.
Launching the app
For the next piece this is as simple as the syntax you already have for running a scheduled task. If you want to run as a domain account and run as an administrator, just make the domain account a member of the 'Administrators' group on the system.
Running in Foreground
Here is the wrinkle, but I don't understand why this is an issue. Scheduled Tasks will only run in the Foreground when a user is logged into the machine.
This option is there so that you can make an app appear in the user's session when they log onto a computer, for things like Kiosk apps, or Point-Of-sale systems, dashboard displays and that sort of thing.
If you set an app to run whether or not a user is logged in, then it always will run in the background.
Are you sure this matters?
Making an app run in the foreground on boot If you want an app to run without having to login, it will run in the background.
If you really want it to run in the foreground, then just set the machine to automatically log in. If it automatically log's in, then it will login and show the desktop, and then the scheduled task can be changed to 'Run only when a user is logged in', which will make it run in the foreground.
But why would someone need an App within a VM, which is by nature headless to run in the foreground?