none
Run scriptblock as administrator and return value RRS feed

  • Question

  • I need to create a Task Scheduler task that requires elevated rights in Windows 10. I use the following trick in Powershell, here's the basic structure:

    $ScriptBlock = { param ([string]$Param1, [string]$Param2 ) Write-Host "Argument 1: " $Param1 Write-Host "Argument 2: " $Param2

    # Do some stuff

    } $A = "Text" $B = "Text with spaces" $Arglist = '-Param1 ' + $A + ' -Param2 ' + "`'$B`'" Start-Process powershell -ArgumentList "-command & {$ScriptBlock} $Arglist" -Verb Runas -Wait

    I can run this scriptblock in a new instance of Powershell as administrator, I can pass parameters to it, but how can I return some values?

    It tired adding -PassThrough parameter to Start-Process and adding exit 123 to the scriptblock, that works, at least I can have an exit code, but I need to reuse this SB for non-elevated tasks as well, so if I run it like & $Scriptnlock $Arglist - it stops the script. 

    I tried adding environmental variables to the SB, like [environment]::SetEnvironmentVariable('MyFlag', 'YES') but they are kept only within one session.

    I investigated  PSJobs, they have ways to return value, they can share a sync hashtable across instances, but I haven't found a way to run them as admin.

    Certainly I can output what I need to a file and open it when 'as admin' task is done but that's not a very elegant solution for a couple of values I need to pass as a result.

    So are there any other ways to pass results from another instance of Powershell?

    Saturday, March 4, 2017 11:11 AM

Answers

All replies

  • You can't run elevated in the same session. You must start the first instance elevated and work from there.

    If you elevate a process it will always force a new console.


    \_(ツ)_/

    Saturday, March 4, 2017 1:22 PM
  • Elevation is per-process. You cannot automatically elevate without provoking the UAC prompt (see the You cannot bypass the UAC prompt post at the top of this forum).

    -- Bill Stewart [Bill_Stewart]

    Saturday, March 4, 2017 11:53 PM
    Moderator