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


All replies