Run powershell command as currently logged in user
Given a powershell script that runs as Local System ( nt authoritysystem
).
Is there a way to execute a command as the currently logged in user (without specifying the user password of course) ?
From what I've experimented so far is the Register-ScheduledTask
cmdlet which takes an -User
param. The task was scheduled and run successfully, but only works when the user is logged in.
Is there a better way to do it ?
There is a complicated and round-about way of doing exactly this. It involves the API function CreateProcessAsUser
. In order to call it, you need to obtain the TOKEN
associated with the current console session, which can be done with the WTSQueryUserToken
API function. This takes a session ID, which is obtained with the WTSGetActiveConsoleSessionId
API function. (Many examples then show the token being duplicated, but from what I've read, this is unnecessary since WTSQueryUserToken
already returns a primary token.)
You also need to initialize an environment block for the process you're going to create. For that, you use the CreateEnvironmentBlock
API function. Make sure you specify the CREATE_UNICODE_ENVIRONMENT
flag.
Of course, PowerShell cannot call these functions directly -- so you will have to dynamically compile some C# helper code and load it into the PowerShell environment.
I use schtasks.exe. I am not sure if this can be done in pure PS.
$user = Get-WmiObject -Class win32_computersystem | % Username
$computer = $env:COMPUTERNAME
$time = (Get-Date).AddMinutes(1).ToShortTimeString()
schtasks /create /s $computer /tn "RunCMD" /sc once /tr "cmd.exe" /st $time /ru $user
链接地址: http://www.djcxy.com/p/89664.html