Launching Commands on Behalf of Someone Else

The following script provides a function called Start-ProcessInteractive. You can specify a target computer, a path to an executable on that computer and also some arguments. If you do not specify a path and arguments, then the defaults will run a powershell command and write a file into the target windows folder. That’s a proof-of-concept, because if that command works it illustrates that the PowerShell command was launched with full privileges.

The function schedules the task for the currently logged on user. If no currently logged on user could be identified, then either no user was physically logged on, or the target machine is running virtual machines in which case you can manually submit the user account you want to schedule the command for.

function Start-ProcessInteractive {
param(
$filepath = ‘powershell.exe’,
$arguments = ‘-noprofile -command Get-Date | Out-File $env:windir\testfile.txt’,
[Parameter(Mandatory=$true)]
$computername
)

function Execute-Tool($path) {
$r = (Invoke-Expression $path) 2>&1
if ($LASTEXITCODE -ne 0) { Throw $r[0].Exception.Message }
}

$computername | ForEach-Object {
try {
$username = Get-WmiObject Win32_ComputerSystem -ComputerName $_ |
Select-Object -ExpandProperty UserName
} catch {}
$computer = $_

if ($username -eq $null) {
Write-Warning “On $computername no user is currently physically logged on.”
$username = Read-Host “Enter username of logged on user at the remote system”
}
if ($username -ne ”) {

$xml = @”

IgnoreNew
false
false
true
false
false

true
true
false
false
false
PT72H
7

$filepath
$arguments

$username
InteractiveToken
HighestAvailable

“@

$jobname = ‘remotejob{0}’ -f (Get-Random)

try {
$xml | Out-File “$env:temp\tj1.xml”
Execute-Tool “schtasks /CREATE /TN $jobname /XML $env:temp\tj1.xml /S $computer”
Start-Sleep -Seconds 1
Execute-Tool “schtasks /RUN /TN $jobname /S $computer”
Execute-Tool “schtasks /DELETE /TN $jobname /s $computer /F”
}
catch {
Write-Warning “$_ (trying to access user ‘$username’ on system ‘$computer’)”
}
}
}
}

email me