Invoke-CommandAs icon indicating copy to clipboard operation
Invoke-CommandAs copied to clipboard

Scheduled job can't run for local accounts

Open codaamok opened this issue 2 years ago • 4 comments

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:

image

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".

codaamok avatar Apr 24 '23 18:04 codaamok

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?

mkellerman avatar Apr 25 '23 22:04 mkellerman

No, this line is new:

If ($AsUser) { $JobParameters['Credential'] = $AsUser}

It passes the credential for -AsUser to Register-ScheduledJob.

codaamok avatar Apr 26 '23 07:04 codaamok

Thoughts?

codaamok avatar May 04 '23 16:05 codaamok

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.

mkellerman avatar May 05 '23 17:05 mkellerman