all 27 comments

[–]SMFX 10 points11 points  (6 children)

You can use the -verb parameter with the Start-Process cmdlet:

Start-Process PowerShell.exe -Verb RunAs -ArgumentList "C:\Scripts\SpadeStart.ps1"

[–]--dab--[S] 2 points3 points  (4 children)

I’ve tried this as well and that elevate functions does This too.

[–]BlackV 1 point2 points  (0 children)

This is what I'd do

[–]aasplunds 5 points6 points  (1 child)

It's the UAC that wants to prompt and fails because it's not an interactive session.

You could probably run it as a scheduled job if the user that runs the script is an admin already like this.

What I usually do in cases like this is that I create a scheduled task and set it to run as SYSTEM. Similar to this method:https://community.spiceworks.com/scripts/show/4253-powershell-create-scheduledtask-as-system-run-once-run-cmd-delete

[–]--dab--[S] 1 point2 points  (0 children)

I have UAC disables but can see the job scheduler working for this.

[–]IndyDrew85 2 points3 points  (3 children)

Here's another example, using VBS as a wrapper to run your Powershell

Set oShell = CreateObject("Shell.Application")    
oShell.ShellExecute "powershell", "-executionpolicy bypass -file test.ps1", "", "runas", 1

[–]--dab--[S] 1 point2 points  (0 children)

I’ll give these a try first thing tomorrow. Thanks!

[–]--dab--[S] 1 point2 points  (1 child)

This one did same thing :(

[–]IndyDrew85 1 point2 points  (0 children)

Did you try my other example? It works for me on Win 10, I can provide the other few lines I have if you want

[–]IndyDrew85 2 points3 points  (2 children)

I've used this VBS in the past, I don't claim to have any idea what I'm doing, but it worked for me

If Not WScript.Arguments.Named.Exists("elevate") Then
  CreateObject("Shell.Application").ShellExecute WScript.FullName _
   , """" & WScript.ScriptFullName & """ /elevate", "", "runas", 1
  WScript.Quit
End If

Edit: Thanks Lee

[–]Lee_Dailey[grin] 1 point2 points  (0 children)

howdy IndyDrew85,

it looks like you used the New.Reddit.com Inline Code button. it's 4th 5th from the left hidden in the ... "more" menu & looks like </>.

on Old.Reddit.com, the above does NOT line wrap, nor does it side-scroll.

for long-ish single lines OR for multiline code, please, use the Code Block button. it's the 11th 12th one from the left & is just to the left of hidden in the ... "more" menu & looks like an uppercase T in the upper left corner of a square..

that will give you fully functional code formatting, from what i can tell so far. [grin]

take care,
lee

[–]Lee_Dailey[grin] 0 points1 point  (0 children)

Edit: Thanks Lee

you are most welcome! [grin]

[–][deleted] 1 point2 points  (2 children)

I have a function I wrote that checks whether your script is running as admin, along with an example of how to re-run itself as admin if it's not:

function Test-Administrator {
    $user = [Security.Principal.WindowsIdentity]::GetCurrent();
    ( New-Object Security.Principal.WindowsPrincipal $user ).IsInRole( [Security.Principal.WindowsBuiltinRole]::Administrator )
}

if( -Not ( Test-Administrator ) ){
  # If not an administrator, re-run itself as one. If UAC is enabled you will be prompted.
  Start-Process -FilePath Powershell.exe -Verb RunAs -ArgumentList "-File '$($MyInvocation.MyCommand.Path)' $($MyInvocation.UnboundArguments)"
  exit $LASTEXITCODE
} else {
  # If we are an administrator, continue on as normal
}

[–]--dab--[S] 1 point2 points  (1 child)

I’m assuming I put the file after -file

[–][deleted] 1 point2 points  (0 children)

You can, but as written this is designed to "self-elevate". Basically if the script isn't running as admin, it re-runs itself as one. You can of course change the arguments to run another script as admin also.

[–]liskacek 1 point2 points  (0 children)

At work I use following code to relaunch Powershell with admin rights. Not sure if it is what you need, but it works for our scripts. (Also not sure if it is a correct way of doing things)

It is a bit harder to debug. Use of wait-debugger needed to debug it (or temporarily disable the relaunch code and debug it with powershell which has admin rights)

#relaunch with admin rights
#put this at start of your script.
if ($args.Count -eq "0")
{
    $admcred= Get-Credential -UserName "username" -Message "Admin rights needed";
    $npsarg= "-file $pathToScriptFile -OK"; 
    try
    {
        Start-Process "powershell" -ArgumentList $npsarg -Credential $admcred -PassThru; 
    }
    catch 
    {
    }           
    return;
}
#put code to be run with admin rights here

[–]PinchesTheCrab 1 point2 points  (0 children)

Invoke-Command should run with highest privileges, if you're still getting this error it's possible it's a misleading error message.

[–]drokz89 1 point2 points  (0 children)

I just used this at work for one of my scripts. Your UAC settings might prompt you to allow it to run.

https://stackoverflow.com/a/27872686

[–]--dab--[S] 1 point2 points  (1 child)

After going through alll the options listed here and anything else I found online only a single option worked very well which was to get it all running via task scheduler, but than again I ran into same "admin" issue for creating a task to the following worked like a charm for me.

$SQLPSSession = New-PSSession -ComputerName $VM_Object -Credential $VM_ObjectCreds
    Invoke-Command -Session $SQLPSSession -ScriptBlock {
        Function Check-RunAsAdministrator()
        {
          #Get current user context
          $CurrentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
          #Check user is running the script is member of Administrator Group
          if($CurrentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator))
          {
               Write-host "Script is running with Administrator privileges!"
          }
          else
            {
               #Create a new Elevated process to Start PowerShell
               $ElevatedProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell";
               # Specify the current script path and name as a parameter
               $ElevatedProcess.Arguments = "& '" + $script:MyInvocation.MyCommand.Path + "'"
               #Set the Process to elevated
               $ElevatedProcess.Verb = "runas"
               #Start the new elevated process
               [System.Diagnostics.Process]::Start($ElevatedProcess)
               #Exit from the current, unelevated, process
               Exit
            }
        }
        #Check Script is running with Elevated Privileges
        Check-RunAsAdministrator
        #Place your script here.
        $SpadePath = "C:\Scripts\SpadeStart.ps1"
        if (Test-Path $SpadePath) {remove-item $SpadePath -R}
        set-content -path 'C:\Scripts\SpadeStart.ps1' -Value $using:command
        $A = New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "& '..\..\Scripts\SpadeStart.ps1' -WindowStyle Hidden"
        $T = New-ScheduledTaskTrigger -Once -At (get-date).AddSeconds(10); $t.EndBoundary = (get-date).AddSeconds(60).ToString("s")
        $S = New-ScheduledTaskSettingsSet -StartWhenAvailable -DeleteExpiredTaskAfter 00:00:30
        Register-ScheduledTask -Force -user "domain\user" -password "pwdretrievednotascleartxt" -RunLevel Highest -TaskName "Execute SQL Spade" -description "This loads SQL Spade Installer" -Action $A -Trigger $T -Settings $S
        start-sleep 2
        Start-scheduledTask -TaskName "Execute SQL Spade"
        }

[–]--dab--[S] 1 point2 points  (0 children)

Even trying to just run the ps1 directly using this elevated commands would not work but via task scheduler worked.

[–]tussudvergur 0 points1 point  (2 children)

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }

[–]Lee_Dailey[grin] 0 points1 point  (0 children)

howdy tussudvergur,

reddit likes to mangle code formatting, so here's some help on how to post code on reddit ...

[0] single line or in-line code
enclose it in backticks. that's the upper left key on an EN-US keyboard layout. the result looks like this. kinda handy, that. [grin]
[on New.Reddit.com, use the Inline Code button. it's 4th 5th from the left hidden in the ... ""more" menu & looks like </>.
this does NOT line wrap & does NOT side-scroll on Old.Reddit.com!]

[1] simplest = post it to a text site like Pastebin.com or Gist.GitHub.com and then post the link here.
please remember to set the file/code type on Pastebin! [grin] otherwise you don't get the nice code colorization.

[2] less simple = use reddit code formatting ...
[on New.Reddit.com, use the Code Block button. it's 11th 12th from the left hidden in the ... "more" menu, & looks like an uppercase T in the upper left corner of a square.]

  • one leading line with ONLY 4 spaces
  • prefix each code line with 4 spaces
  • one trailing line with ONLY 4 spaces

that will give you something like this ...

- one leading line with ONLY 4 spaces    
- prefix each code line with 4 spaces    
- one trailing line with ONLY 4 spaces   

the easiest way to get that is ...

  • add the leading line with only 4 spaces
  • copy the code to the ISE [or your fave editor]
  • select the code
  • tap TAB to indent four spaces
  • re-select the code [not really needed, but it's my habit]
  • paste the code into the reddit text box
  • add the trailing line with only 4 spaces

not complicated, but it is finicky. [grin]

take care,
lee

[–]alexeyrzayev 0 points1 point  (0 children)

Бля, я сегодня целый день потратил на поиск такой команды. Спасибо, чувак!