Processasuser question regarding scheduled task

Im trying to make a PSADT that creates a scheduled task that will run at logon for the users.

I have set require admin to on in psadt config and wants to run it in system context if possible. Can this be achieved?

Its copying the script that needs to be run in to HCKU into programfiles\customerfolder

Then in PSADT creates the scheduled task like this:

        $Username = "$env:USERNAME"
        $A = New-ScheduledTaskAction -Execute "$PSHOME\powershell.exe" -Argument "-ExecutionPolicy Bypass -WindowStyle Hidden -File `"${env:ProgramFiles(x86)}\Companyname\SharePointAutoMountRegAdd.ps1`"" -WorkingDirectory "${env:ProgramFiles(x86)}\Companyname"
        $T = New-ScheduledTaskTrigger -AtLogon
        $P = New-ScheduledTaskPrincipal -UserId "$Username" -RunLevel Highest
        $S = New-ScheduledTaskSettingsSet -Compatibility Win8
        $D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S
        Register-ScheduledTask -TaskName SetRegForSharePointMapping -InputObject $D -User "$Username" -TaskPath "\Microsoft\Intune\"

Then in install it will run this:

Execute-ProcessAsUser -Path "$PSHOME\powershell.exe" -Parameters "-Command & { & `"${env:ProgramFiles(x86)}\Companyname\SharePointAutoMountRegAdd.ps1`"; Exit `$LastExitCode }" -Wait

Will this work?

Have you tried it out? I don’t have a working example of what you’re trying to achieve but my immediate thoughts are:

One thing that stick out that could be an issue is that when you define the scheduled task, you are telling it to run as $env:USERNAME, which will be in the context of the system account, when you in fact want the task to run in user context each time. Maybe try and give the Users / Authenticated Users group instead.

Secondly, once you’ve defined a task that can run in user context, rather than use Execute-ProcessAsUser, which creates yet another scheduled task (albeit a temporary one) to execute a command, I would try to see if you could just trigger the task you just created in the previous step instead.

1 Like