1

What I am looking to do is open an elevated PS instance from an already open PS instance and then pipe the command from the clipboard to the prompt not just the window.

S.Raines
  • 17
  • 3

1 Answers1

0

1) Copy and Paste with Clipboard from PowerShell;
2) Run with elevated permissions.
Combining the first with the second will give the desired result.
The following script copies a string with an one-liner to the clipboard, receives the one-liner from the clipboard and pass it for execution to powershell.exe, which is launched with elevated rights.
Warning: be careful with double quotes.

$re = '^\S+\s+\S+\s+S-1-5-32-544'
"whoami.exe /groups | Select-String \""${re}\""" | clip.exe
Add-Type -AssemblyName System.Windows.Forms
$dummy = New-Object System.Windows.Forms.TextBox
$dummy.Multiline = $true
$dummy.Paste()
$command = $dummy.Text
$args = '-NoLogo', '-NoProfile', '-NoExit', "-Command ${command}"
Start-Process -FilePath powershell.exe -Verb runas -ArgumentList $args

The following script demonstrates that it is possible to pass multi-line script blocks.
The script will launch itself three times and stops.

& ($b = {
Write-Host $b
$re = '^\S+\s+\S+\s+S-1-5-32-544'
whoami.exe /groups | Select-String $re
if( $b -match 'return\s\}###' ) { return }
'&($b = {' + ($b -replace 'return\s\}', '$0#') + '})' | clip.exe
Add-Type -AssemblyName System.Windows.Forms
$dummy = New-Object System.Windows.Forms.TextBox
$dummy.Multiline = $true
$dummy.Paste()
$command = $dummy.Text
$args = '-NoLogo', '-NoProfile', '-NoExit'
$args += '-Command {0}' -f $command
Start-Process -FilePath powershell.exe -Verb runas -ArgumentList $args
})
Andrei Odegov
  • 2,599
  • 2
  • 14
  • 20