Invoke-CommandAs
Invoke-CommandAs copied to clipboard
Scheduled job can't run for local accounts
I discovered when trying to run a script block with -AsUser, where the credential is a local user account*, the scheduled job just wouldn't run. powershell.exe would return with an exit code 1 from task scheduler.
Code example is below to repro, however it's important you use a local, non-domain joined, account for the cred.
$cred = Get-Credential
Invoke-CommandAs -ScriptBlock { whoami } -AsUser $cred
It doesn't seem to be an issue for domain accounts, and I don't know enough about Windows like this to rationalise it. However, through debugging I did find once I passed the -RunAs credential to the Register-ScheduledJob in Invoke-ScheduledTask, the scheduled job would be successfully invoked by task scheduler.
* In order to get a local user account to work, you will need to grant the local user account SeBatchLogonRight rights, more info. Can be configured locally w/o GPO using secpol.msc:

As an aside, I did a minor cleanup in Invoke-ScheduledTask to initialise a couple of hashtables with a value, rather than initialising the hashtables and then defining values in them - no reason other than "meh".
Other than the minor cleanup, this seems to be more of a documentation issue, since you're not doing any correction to the code. Am i right?
No, this line is new:
If ($AsUser) { $JobParameters['Credential'] = $AsUser}
It passes the credential for -AsUser to Register-ScheduledJob.
Thoughts?
Sorry, i havent had the time to think though this step. Basically, the main credential is used to authenticate to the remote computer. and the AsUser is used to run the script 'as' that user. I think this change would alter the expected behaviour.