mkellerman / Invoke-CommandAs

Invoke Command As System/Interactive/GMSA/User on Local/Remote machine & returns PSObjects.
https://www.powershellgallery.com/packages/Invoke-CommandAs/
MIT License
455 stars 71 forks source link

Scheduled job can't run for local accounts #62

Open codaamok opened 1 year ago

codaamok commented 1 year ago

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

mkellerman commented 1 year ago

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?

codaamok commented 1 year ago

No, this line is new:

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

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

codaamok commented 1 year ago

Thoughts?

mkellerman commented 1 year ago

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.