Skip to content

Instantly share code, notes, and snippets.

@sweeneyrobb
Forked from yangyer/Start-ExecuteUAC.ps1
Last active February 1, 2016 19:43
Show Gist options
  • Save sweeneyrobb/9b3ab676cc5f9b1f1d30 to your computer and use it in GitHub Desktop.
Save sweeneyrobb/9b3ab676cc5f9b1f1d30 to your computer and use it in GitHub Desktop.
Powershell sudo
function Start-ElevatedUACSession {
$outputFiles = @{
Standard = [System.IO.Path]::GetTempFileName();
Error = [System.IO.Path]::GetTempFileName();
}
$cmd = [string]::Join(" ", $args)
Write-Host "Executing Elevated: $cmd"
Start-Process powershell -Verb "runAs" -WindowStyle Hidden -Wait -ArgumentList "/Command ""& { $cmd > '$($outputFiles.Standard)' }"""
Get-Content $outputFiles.Standard
$outputFiles.Values | Remove-Item
}
Set-Alias sudo Start-ElevatedUACSession
function New-SuperUserSession() {
$signatureGet = @'
[DllImport(@"user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
'@
$win = Add-Type -Name win -MemberDefinition @'
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
'@ -Passthru
$typeFunc = Add-Type -MemberDefinition $signatureGet -Name "Test" -PassThru
$currentProc = [System.Diagnostics.Process]::GetCurrentProcess()
$ignore = $typeFunc::ShowWindow($currentProc.MainWindowHandle, 0)
$evelvatedProc = Start-Process powershell -Verb 'runAs' -WindowStyle Normal -PassThru -Wait -WorkingDirectory ~
$ignore = $typeFunc::ShowWindow($currentProc.MainWindowHandle, 5)
$ignore = $win::SetForegroundWindow($currentProc.MainWindowHandle)
}
Set-Alias sudo-su New-SuperUserSession
@sweeneyrobb
Copy link
Author

bunch of things need to be changed here but works well enough for now. might be a fun weekend project to nail down and turn into a module.

  • better way to capture errors
  • hanging wait if the cmd requires input

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment