How can I run commands in PowerShell with Administrator permissions?

9,785

Solution 1

Usually when I see powershell immediately close, its a problem with the Execution Policy. clicking the Orb, typing Powershell then Right Clicking the link, and "run as Administrator" and have it open that way?

You can then, to see whats going on, navigate to the folder where your script is, and do a ./NameofScript.ps1

Solution 2

If you are already in powershell, type: Start-Process powershell -verb runas

I write a sudo function to accomplish more powerful things, like executing something elevated and get the result in the same shell, for example:

sudo {rm fileThatNeedElevatedRightsToBeDeleted; ls}

Here is the code:

function sudo(){
param([String] $code)
$viejos = gps powershell
$here = add-quotes (get-location).path
$resultPath = [IO.Path]::GetTempPath() + "temp.result.xml";

$code = "set-location $here; function Run{$code};Run $args|Export-Clixml $resultPath" 

$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($code))

start-process PowerShell.exe -verb Runas -argumentlist '-encodedCommand',$encoded

$nuevos = gps powershell
$array = New-Object Collections.Generic.List[int]
$array2 = New-Object Collections.Generic.List[int]
$viejos | %{$array.add($_.ID)}
$nuevos | %{$array2.add($_.ID)}
$idTowait = $array2 | ?{$array -notcontains $_}
while(1){
    $nuevos = gps powershell
    $array2.Clear()
    $nuevos | %{$array2.add($_.ID)}
    if($array2 -contains $idTowait)
        {sleep -Milliseconds 500}
    else
        {break;}
}

if(Test-Path $resultPath){
  if((gi $resultPath).length)
  {        
      Import-Clixml $resultPath 
      rm $resultPath     
  }
}
else
    {"No results"};
}
Share:
9,785

Related videos on Youtube

Jonas
Author by

Jonas

I'm a Computer Science student.

Updated on September 17, 2022

Comments

  • Jonas
    Jonas over 1 year

    I would like to run commands in PowerShell with Administrator permissions? How can I do that?

    I have tried to start PowerShell with the runas command, but PowerShell is closed immediately after I have typed a password.

    I use Windows 7 and I am the only user on the computer.

    • vapcguy
      vapcguy almost 9 years
      Duplicate question - superuser.com/questions/108207/…
    • RaSedg
      RaSedg about 4 years
      You can use gsudo to elevate PowerShell commands: $hash = gsudo "(Get-FileHash ./protectedfile).Hash""
  • Jonas
    Jonas over 13 years
    What is the Orb that I should click?
  • uxout
    uxout over 13 years
    I have no clue. I like yours, actually. ;) (Also, sorry, I forgot to +1 before I was so busy being clever, ahah)
  • uxout
    uxout over 13 years
    ...actually, the Help files in Win7 still call it the "Start button". Guess that's official.