Showing the UAC prompt in PowerShell if the action requires elevation - powershell

I have a simple PowerShell script to stop a process:
$p = get-process $args
if ( $p -ne $null )
{
$p | stop-process
$p | select ProcessName, ID, HasExited, CPU, Handles
}
else { "No such process" }
If I try to stop a process not started by the current user; it works on Windows Server 2003. However, on Windows Server 2008 (and other Windows flavours with User Account Control), I get the following error:
Stop-Process : Cannot stop process "w3wp (5312)" because of the following error: Access is denied
Is there any way to get around this without running PowerShell with elevated privileges ? It would be OK if the user was just presented with the UAC prompt, whenever he tries to execute an action, that requires elevation.

AFAIK, there is no way to do it in the sense that you seem to want. That is running a specified .exe and expecting a prompt to appear immediately.
What I do is for commands that I know have to be run with administrative privs, I run them with a functions I have laying around called Invoke-Admin. It ensures that I'm running as admin and will prompt the user with the UAC dialog if i'm not before running the command.
Here it is
function Invoke-Admin() {
param ( [string]$program = $(throw "Please specify a program" ),
[string]$argumentString = "",
[switch]$waitForExit )
$psi = new-object "Diagnostics.ProcessStartInfo"
$psi.FileName = $program
$psi.Arguments = $argumentString
$psi.Verb = "runas"
$proc = [Diagnostics.Process]::Start($psi)
if ( $waitForExit ) {
$proc.WaitForExit();
}
}

First install PowerShell Community Extensions choco install pscx via Chocolatey (you may have to restart your shell environment)
then enable pscx
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser #allows scripts to run from the interwebs, such as pcsx
Then use Invoke-Elevated, for example
Invoke-Elevated {Add-PathVariable $args[0] -Target Machine} -ArgumentList $MY_NEW_DIR

This script sectio check for the Medium Mandatory level token (non elevated admin) and restarts the script elevated.
if ($Mygroups -match ".*Mandatory Label\\Medium Mandatory Level") {
#non elevated admin: elevating
write-host "Elevate"
start-process powershell -Argumentlist "$PSCommandPath -Yourargument $Youragumentvalue" -verb runas -Wait
exit
}

Related

Running PowerShell with admin credentials for users

I have a PowerShell script that restarts the Spooler service, then locates all printers with a specific name, removes those printers, then adds the printers back. I want to be able to go on a user's PC and run the script and input my admin credentials, but when I do, it doesn't find the printers because printers are per user not per PC. Is there a way to run the script as the user with elevated permissions in a single PS instance?
# Check if ps is running as admin otherwise open this script as admin
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 }
# Local printer name to search for
$FindName = "*DSM*"
# Store local printer object for later use
$Printers = Get-Printer -Name $FindName
if(!$Printers){
$NotFound = "No printer with the name "
$NotFound2 = " was found."
$NotFound + $FindName + $NotFound2
}else{
Write-Output "Printer found"
# Restart spooler service
Write-Output "Restarting Spooler"
Restart-Service -Name Spooler -Force
# Wait for Spooler to come back online
Start-Sleep -s 5
# loop through all printers found and re-add each one
foreach($Printer in $Printers){
# Remove printer
Write-Output "`nRemoving " $Printer.Name
Remove-Printer -Name $Printer.Name
# Add printer
Write-Output "Re-adding " $Printer.Name
Add-Printer -ConnectionName $Printer.Name
}
Read-Host -Prompt "Press Enter to exit"
}
Basically, you need to run the service management pieces as an admin user (presumably, end users don't have admin on their workstations) but the printer management must happen from the end user's account. You'll essentially use Start-Process to run the service management piece as your admin account, but let the rest of the script run in the end user's context:
# Restart spooler Service
# Splatting used here for readability
$psPath = "$env:SystemRoot/System32/WindowsPowerShell/v1.0/powershell.exe"
$spArgs = #{
Wait = $True
Credential = Get-Credential DOMAIN.tld\adminuser
FilePath = $psPath
ArgumentList = '-Command "$p = Start-Process -PassThru -Wait -FilePath \"{0}\" -Verb RunAs -ArgumentList \"Restart-Service -Force -EA Stop spooler\"; exit $p.ExitCode"' -f $psPath
PassThru = $True
ErrorAction = 'Stop'
}
$p = Start-Process #spArgs
if( $p.ExitCode -ne 0 ) {
# The service failed to restart. Handle the failure case.
}
The way this works:
Run a new powershell.exe process as your admin user, then making sure to elevate permissions by running powershell.exe a second time with the RunAs Verb. You will need to input the credential each time the script is run.
As indicated in the comments, -Credential and -Verb are mutually exclusive.
There is not really a graceful way to do this, to make this most readable I have use a literal string with the format operator -f to avoid an even worse escape-hell.
The -Command parameter needs to be provided within double-quotes when executed via Start-Process, or else it will only render the literal string and not actually execute the nested command.
The youngest PowerShell process will perform the service restart.
Use the -Wait flag to wait until the process exits for both invocations of Start-Process. Start-Process does not block execution by default regardless of application type.
Make Restart-Service throw a terminating error with -EA Stop if it encounters a problem. This will guarantee a non-zero exit code is returned on failure without requiring additional boilerplate code.
Specifying the full path to powershell.exe is optional but a general good practice. You could also simply use powershell.exe in place of the full path to the binary.
Programs run with Start-Process do not set $LASTEXITCODE. Therefore, we return the Process object with -Passthru, then check that its exit code is 0. Any other exit code indicates failure for this operation.
You can remove your admin check from the script since this no longer needs administrative permissions, and Get-Credential will essentially elevate for the service restart.
Note that if you want to perform this from a user who can elevate but you don't want the PowerShell script itself to run elevated, you can run the script without elevation and use the technique above but omit the -Credential parameter which becomes redundant. It would still work but no reason to authenticate when you don't have to.

Running Powershell script as Administrator (RunAs) [duplicate]

You know how if you're the administrative user of a system and you can just right click say, a batch script and run it as Administrator without entering the administrator password?
I'm wondering how to do this with a PowerShell script. I do not want to have to enter my password; I just want to mimic the right-click Run As Administrator method.
Everything I read so far requires you to supply the administrator password.
If the current console is not elevated and the operation you're trying to do requires elevated privileges then you can start powershell with the Run as Administrator option :
PS> Start-Process powershell -Verb runAs
Microsoft Docs: Start-Process
Here is an addition to Shay Levi's suggestion (just add these lines at the beginning of a script):
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$arguments = "& '" +$myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
This results in the current script being passed to a new powershell process in Administrator mode (if current User has access to Administrator mode and the script is not launched as Administrator).
Self elevating PowerShell script
Windows 8.1 / PowerShell 4.0 +
One line :)
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 }
# Your script here
Benjamin Armstrong posted an excellent article about self-elevating PowerShell scripts. There a few minor issue with his code; a modified version based on fixes suggested in the comment is below.
Basically it gets the identity associated with the current process, checks whether it is an administrator, and if it isn't, creates a new PowerShell process with administrator privileges and terminates the old process.
# Get the ID and security principal of the current user account
$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent();
$myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID);
# Get the security principal for the administrator role
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator;
# Check to see if we are currently running as an administrator
if ($myWindowsPrincipal.IsInRole($adminRole))
{
# We are running as an administrator, so change the title and background colour to indicate this
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)";
$Host.UI.RawUI.BackgroundColor = "DarkBlue";
Clear-Host;
}
else {
# We are not running as an administrator, so relaunch as administrator
# Create a new process object that starts PowerShell
$newProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell";
# Specify the current script path and name as a parameter with added scope and support for scripts with spaces in it's path
$newProcess.Arguments = "& '" + $script:MyInvocation.MyCommand.Path + "'"
# Indicate that the process should be elevated
$newProcess.Verb = "runas";
# Start the new process
[System.Diagnostics.Process]::Start($newProcess);
# Exit from the current, unelevated, process
Exit;
}
# Run your code that needs to be elevated here...
Write-Host -NoNewLine "Press any key to continue...";
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown");
Here's a self-elevating snippet for Powershell scripts which preserves the working directory:
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
exit;
}
# Your script here
Preserving the working directory is important for scripts that perform path-relative operations. Almost all of the other answers do not preserve this path, which can cause unexpected errors in the rest of the script.
If you'd rather not use a self-elevating script/snippet, and instead just want an easy way to launch a script as adminstrator (eg. from the Explorer context-menu), see my other answer here: https://stackoverflow.com/a/57033941/2441655
You can create a batch file (*.bat) that runs your powershell script with administrative privileges when double-clicked. In this way, you do not need to change anything in your powershell script.To do this, create a batch file with the same name and location of your powershell script and then put the following content in it:
#echo off
set scriptFileName=%~n0
set scriptFolderPath=%~dp0
set powershellScriptFileName=%scriptFileName%.ps1
powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"%scriptFolderPath%`\"; & \`\".\%powershellScriptFileName%\`\"`\"\" -Verb RunAs"
That's it!
Here is the explanation:
Assuming your powershell script is in the path C:\Temp\ScriptTest.ps1, your batch file must have the path C:\Temp\ScriptTest.bat. When someone execute this batch file, the following steps will occur:
The cmd will execute the command
powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"C:\Temp\`\"; & \`\".\ScriptTest.ps1\`\"`\"\" -Verb RunAs"
A new powershell session will open and the following command will be executed:
Start-Process powershell "-ExecutionPolicy Bypass -NoProfile -NoExit -Command `"cd \`"C:\Temp\`"; & \`".\ScriptTest.ps1\`"`"" -Verb RunAs
Another new powershell session with administrative privileges will open in the system32 folder and the following arguments will be passed to it:
-ExecutionPolicy Bypass -NoProfile -NoExit -Command "cd \"C:\Temp\"; & \".\ScriptTest.ps1\""
The following command will be executed with administrative privileges:
cd "C:\Temp"; & ".\ScriptTest.ps1"
Once the script path and name arguments are double quoted, they can contain space or single quotation mark characters (').
The current folder will change from system32 to C:\Temp and the script ScriptTest.ps1 will be executed. Once the parameter -NoExit was passed, the window wont be closed, even if your powershell script throws some exception.
Using
#Requires -RunAsAdministrator
has not been stated, yet. It seems to be there only since PowerShell 4.0.
http://technet.microsoft.com/en-us/library/hh847765.aspx
When this switch parameter is added to your requires statement,
it specifies that the Windows PowerShell session in which you are
running the script must be started with elevated user rights
(Run as Administrator).
To me, this seems like a good way to go about this, but I'm not sure of the field experience, yet. PowerShell 3.0 runtimes probably ignore this, or even worse, give an error.
When the script is run as a non-administrator, the following error is given:
The script 'StackOverflow.ps1' cannot be run because it contains a
"#requires" statement for running as Administrator. The current
Windows PowerShell session is not running as Administrator. Start
Windows PowerShell by using the Run as Administrator option, and then
try running the script again.
+ CategoryInfo : PermissionDenied: (StackOverflow.ps1:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ScriptRequiresElevation
You can easily add some registry entries to get a "Run as administrator" context menu for .ps1 files:
New-Item -Path "Registry::HKEY_CLASSES_ROOT\Microsoft.PowershellScript.1\Shell\runas\command" `
-Force -Name '' -Value '"c:\windows\system32\windowspowershell\v1.0\powershell.exe" -noexit "%1"'
(updated to a simpler script from #Shay)
Basically at HKCR:\Microsoft.PowershellScript.1\Shell\runas\command set the default value to invoke the script using Powershell.
The code posted by Jonathan and Shay Levy did not work for me.
Please find the working code below:
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
#"No Administrative rights, it will display a popup window asking user for Admin rights"
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments
break
}
#"After user clicked Yes on the popup, your file will be reopened with Admin rights"
#"Put your code here"
You need to rerun the script with administrative privileges and check if the script was launched in that mode. Below I have written a script that has two functions: DoElevatedOperations and DoStandardOperations. You should place your code that requires admin rights into the first one and standard operations into the second. The IsRunAsAdmin variable is used to identify the admin mode.
My code is an simplified extract from the Microsoft script that is automatically generated when you create an app package for Windows Store apps.
param(
[switch]$IsRunAsAdmin = $false
)
# Get our script path
$ScriptPath = (Get-Variable MyInvocation).Value.MyCommand.Path
#
# Launches an elevated process running the current script to perform tasks
# that require administrative privileges. This function waits until the
# elevated process terminates.
#
function LaunchElevated
{
# Set up command line arguments to the elevated process
$RelaunchArgs = '-ExecutionPolicy Unrestricted -file "' + $ScriptPath + '" -IsRunAsAdmin'
# Launch the process and wait for it to finish
try
{
$AdminProcess = Start-Process "$PsHome\PowerShell.exe" -Verb RunAs -ArgumentList $RelaunchArgs -PassThru
}
catch
{
$Error[0] # Dump details about the last error
exit 1
}
# Wait until the elevated process terminates
while (!($AdminProcess.HasExited))
{
Start-Sleep -Seconds 2
}
}
function DoElevatedOperations
{
Write-Host "Do elevated operations"
}
function DoStandardOperations
{
Write-Host "Do standard operations"
LaunchElevated
}
#
# Main script entry point
#
if ($IsRunAsAdmin)
{
DoElevatedOperations
}
else
{
DoStandardOperations
}
Adding my 2 cents. My simple version based on net session which works all the time so far in Windows 7 / Windows 10. Why over complicate it?
if (!(net session)) {$path = "& '" + $myinvocation.mycommand.definition + "'" ; Start-Process powershell -Verb runAs -ArgumentList $path ; exit}
just add to the top of the script and it will run as administrator.
You can also force the application to open as administrator, if you have an administrator account, of course.
Locate the file, right click > properties > Shortcut > Advanced and check Run as Administrator
Then Click OK.
This behavior is by design. There are multiple layers of security since Microsoft really didn't want .ps1 files to be the latest email virus. Some people find this to be counter to the very notion of task automation, which is fair. The Vista+ security model is to "de-automate" things, thus making the user okay them.
However, I suspect if you launch powershell itself as elevated, it should be able to run batch files without requesting the password again until you close powershell.
A number of the answers here are close, but a little more work than needed.
Create a shortcut to your script and configure it to "Run as Administrator":
Create the shortcut.
Right-click shortcut and open Properties...
Edit Target from <script-path> to powershell <script-path>
Click Advanced... and enable Run as administrator
Here is how to run a elevated powershell command and collect its output form within a windows batch file in a single command(i.e not writing a ps1 powershell script).
powershell -Command 'Start-Process powershell -ArgumentList "-Command (Get-Process postgres | Select-Object Path | Select-Object -Index 0).Path | Out-File -encoding ASCII $env:TEMP\camp-postgres.tmp" -Verb RunAs'
Above you see i first launch a powershell with elevated prompt and then ask that to launch another powershell(sub shell) to run the command.
C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell is where the shortcut of PowerShell resides. It too still goes to a different location to invoke the actual 'exe' (%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe).
Since PowerShell is user-profile driven when permissions are concerned; if your username/profile has the permissions to do something then under that profile, in PowerShell you would generally be able to do it as well. That being said, it would make sense that you would alter the shortcut located under your user profile, for example, C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell.
Right-click and click properties. Click "Advanced" button under the "Shortcut" tab located right below the "Comments" text field adjacent to the right of two other buttons, "Open File Location" and "Change Icon", respectively.
Check the checkbox that reads, "Run as Administrator". Click OK, then Apply and OK. Once again right click the icon labeled 'Windows PowerShell' located in C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell and select "Pin to Start Menu/Taskbar".
Now whenever you click that icon, it will invoke the UAC for escalation. After selecting 'YES', you will notice the PowerShell console open and it will be labeled "Administrator" on the top of the screen.
To go a step further... you could right click that same icon shortcut in your profile location of Windows PowerShell and assign a keyboard shortcut that will do the exact same thing as if you clicked the recently added icon. So where it says "Shortcut Key" put in a keyboard key/button combination like: Ctrl + Alt + PP (for PowerShell). Click Apply and OK.
Now all you have to do is press that button combination you assigned and you will see UAC get invoked, and after you select 'YES' you will see a PowerShell console appear and "Administrator" displayed on the title bar.
I have found a way to do this...
Create a batch file to open your script:
#echo off
START "" "C:\Scripts\ScriptName.ps1"
Then create a shortcut, on your desktop say (right click New -> Shortcut).
Then paste this into the location:
C:\Windows\System32\runas.exe /savecred /user:*DOMAIN*\*ADMIN USERNAME* C:\Scripts\BatchFileName.bat
When first opening, you will have to enter your password once. This will then save it in the Windows credential manager.
After this you should then be able to run as administrator without having to enter a administrator username or password.
I am using the solution below. It handles stdout/stderr via transcript feature and passes exit code correctly to parent process. You need to adjust transcript path/filename.
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
echo "* Respawning PowerShell child process with elevated privileges"
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "powershell"
$pinfo.Arguments = "& '" + $myinvocation.mycommand.definition + "'"
$pinfo.Verb = "RunAs"
$pinfo.RedirectStandardError = $false
$pinfo.RedirectStandardOutput = $false
$pinfo.UseShellExecute = $true
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
echo "* Child process finished"
type "C:/jenkins/transcript.txt"
Remove-Item "C:/jenkins/transcript.txt"
Exit $p.ExitCode
} Else {
echo "Child process starting with admin privileges"
Start-Transcript -Path "C:/jenkins/transcript.txt"
}
# Rest of your script goes here, it will be executed with elevated privileges
Another simpler solution is that you may also right click on "C:\Windows\System32\cmd.exe" and choose "Run as Administrator" then you can run any app as administrator without providing any password.
The problem with the #pgk and #Andrew Odri's answers is when you have script parameters, specially when they are mandatory. You can solve this problem using the following approach:
The user right-clicks the .ps1 file and selects 'Run with PowerShell': ask him for the parameters through input boxes (this is a much better option than use the HelpMessage parameter attribute);
The user executes the script through the console: allow him to pass the desired parameters and let the console force him to inform the mandatory ones.
Here is how would be the code if the script had the ComputerName and Port mandatory parameters:
[CmdletBinding(DefaultParametersetName='RunWithPowerShellContextMenu')]
param (
[parameter(ParameterSetName='CallFromCommandLine')]
[switch] $CallFromCommandLine,
[parameter(Mandatory=$false, ParameterSetName='RunWithPowerShellContextMenu')]
[parameter(Mandatory=$true, ParameterSetName='CallFromCommandLine')]
[string] $ComputerName,
[parameter(Mandatory=$false, ParameterSetName='RunWithPowerShellContextMenu')]
[parameter(Mandatory=$true, ParameterSetName='CallFromCommandLine')]
[UInt16] $Port
)
function Assert-AdministrativePrivileges([bool] $CalledFromRunWithPowerShellMenu)
{
$isAdministrator = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if ($isAdministrator)
{
if (!$CalledFromRunWithPowerShellMenu -and !$CallFromCommandLine)
{
# Must call itself asking for obligatory parameters
& "$PSCommandPath" #script:PSBoundParameters -CallFromCommandLine
Exit
}
}
else
{
if (!$CalledFromRunWithPowerShellMenu -and !$CallFromCommandLine)
{
$serializedParams = [Management.Automation.PSSerializer]::Serialize($script:PSBoundParameters)
$scriptStr = #"
`$serializedParams = '$($serializedParams -replace "'", "''")'
`$params = [Management.Automation.PSSerializer]::Deserialize(`$serializedParams)
& "$PSCommandPath" #params -CallFromCommandLine
"#
$scriptBytes = [System.Text.Encoding]::Unicode.GetBytes($scriptStr)
$encodedCommand = [Convert]::ToBase64String($scriptBytes)
# If this script is called from another one, the execution flow must wait for this script to finish.
Start-Process -FilePath 'powershell' -ArgumentList "-ExecutionPolicy Bypass -NoProfile -EncodedCommand $encodedCommand" -Verb 'RunAs' -Wait
}
else
{
# When you use the "Run with PowerShell" feature, the Windows PowerShell console window appears only briefly.
# The NoExit option makes the window stay visible, so the user can see the script result.
Start-Process -FilePath 'powershell' -ArgumentList "-ExecutionPolicy Bypass -NoProfile -NoExit -File ""$PSCommandPath""" -Verb 'RunAs'
}
Exit
}
}
function Get-UserParameters()
{
[string] $script:ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Enter a computer name:', 'Testing Network Connection')
if ($script:ComputerName -eq '')
{
throw 'The computer name is required.'
}
[string] $inputPort = [Microsoft.VisualBasic.Interaction]::InputBox('Enter a TCP port:', 'Testing Network Connection')
if ($inputPort -ne '')
{
if (-not [UInt16]::TryParse($inputPort, [ref]$script:Port))
{
throw "The value '$inputPort' is invalid for a port number."
}
}
else
{
throw 'The TCP port is required.'
}
}
# $MyInvocation.Line is empty in the second script execution, when a new powershell session
# is started for this script via Start-Process with the -File option.
$calledFromRunWithPowerShellMenu = $MyInvocation.Line -eq '' -or $MyInvocation.Line.StartsWith('if((Get-ExecutionPolicy')
Assert-AdministrativePrivileges $calledFromRunWithPowerShellMenu
# Necessary for InputBox
[System.Reflection.Assembly]::Load('Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') | Out-Null
if ($calledFromRunWithPowerShellMenu)
{
Get-UserParameters
}
# ... script code
Test-NetConnection -ComputerName $ComputerName -Port $Port
I recently needed this to build an environment on ansible. I say right away - the decision is not mine, but I don’t remember where I got it. Looks like that:
powershell.exe -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -Command Get-Service -Name ssh-agent | Set-Service -StartupType Automatic' -Verb RunAs}";
This example enables ssh-agent autostart.
The required command is specified after -Command. The only problem is the launch happens on a new PS instance, but so far this is the only way that I know to execute the command as an admin without additional steps.
The most reliable way I've found is to wrap it in a self-elevating .bat file:
#echo off
NET SESSION 1>NUL 2>NUL
IF %ERRORLEVEL% EQU 0 GOTO ADMINTASKS
CD %~dp0
MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 0); close();"
EXIT
:ADMINTASKS
powershell -file "c:\users\joecoder\scripts\admin_tasks.ps1"
EXIT
The .bat checks if you're already admin and relaunches the script as Administrator if needed. It also prevents extraneous "cmd" windows from opening with the 4th parameter of ShellExecute() set to 0.
On top of Shay Levy's answer, follow the below setup (just once)
Start a PowerShell with Administrator rights.
Follow Stack Overflow question PowerShell says “execution of scripts is disabled on this system.”.
Put your .ps1 file in any of the PATH folders, for example. Windows\System32 folder
After the setup:
Press Win + R
Invoke powershell Start-Process powershell -Verb runAs <ps1_file>
You can now run everything in just one command line. The above works on Windows 8 Basic 64-bit.
I haven't seen my own way of doing it before, so, try this out. It is way easier to follow and has a much smaller footprint:
if([bool]([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -notcontains "S-1-5-32-544") {
Start Powershell -ArgumentList "& '$MyInvocation.MyCommand.Path'" -Verb runas
}
Very simply, if the current Powershell session was called with administrator privileges, the Administrator Group well-known SID will show up in the Groups when you grab the current identity. Even if the account is a member of that group, the SID won't show up unless the process was invoked with elevated credentials.
Nearly all of these answers are a variation on Microsoft's Ben Armstrong's immensely popular method of how to accomplish it while not really grasping what it is actually doing and how else to emulate the same routine.
To append the output of the command to a text filename which includes the current date you can do something like this:
$winupdfile = 'Windows-Update-' + $(get-date -f MM-dd-yyyy) + '.txt'
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -Command `"Get-WUInstall -AcceptAll | Out-File $env:USERPROFILE\$winupdfile -Append`"" -Verb RunAs; exit } else { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -Command `"Get-WUInstall -AcceptAll | Out-File $env:USERPROFILE\$winupdfile -Append`""; exit }
This is a clarification ...
The powershell RUNAS / SAVECRED credential "is not safe", tried it and it adds the admin identity and password into the credential cache and can be used elsewhere OOPS!. If you have done this I suggest you check and remove the entry.
Review your program or code because the Microsoft policy is you cannot have mixed user and admin code in the same code blob without the UAC (the entry point) to execute the program as admin. This would be sudo (same thing) on Linux.
The UAC has 3 types, dont'see, a prompt or an entry point generated in the manifest of the program. It does not elevate the program so if there is no UAC and it needs admin it will fail. The UAC though as an administrator requirement is good, it prevents code execution without authentication and prevents the mixed codes scenario executing at user level.
Elevated PowerShell from Start>Run
You cannot run elevated powershell from the "run" command, in 2012R2 or 2016, without shelling twice:
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell -Command "saps PowerShell -Verb RunAs "
It turns out it was too easy. All you have to do is run a cmd as administrator. Then type explorer.exe and hit enter. That opens up Windows Explorer.
Now right click on your PowerShell script that you want to run, choose "run with PowerShell" which will launch it in PowerShell in administrator mode.
It may ask you to enable the policy to run, type Y and hit enter. Now the script will run in PowerShell as administrator. In case it runs all red, that means your policy didn't take affect yet. Then try again and it should work fine.

Elevated PS script in Jenkins

I have been trying to run a script from a Windows Jenkins (slave) server. The script is written in PowerShell and requires elevated privileges (such as if one right-clicked on PS and selected run-as-administrator).
Jenkins launches its scripts the following way:
powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Users\JOHAN.DER\AppData\Local\Temp\2\hudson9084956499652818911.ps1'"
My script fails because it requires elevated privileges. How can I spawn a new elevated-privileged PS process (that does not require clicking because Jenkins can't do that) that could run my script?
Cheers!
The snippet below checks if current process is elevated and if not, it spawns a new, privileged process. It is little tricky to get output of the child powershell process, so I'm using transcript command to capture it. Below you can find my pipeline definition step:
powershell """
cd "${env.WORKSPACE}"
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
echo "* Respawning PowerShell child process with elevated privileges"
\$pinfo = New-Object System.Diagnostics.ProcessStartInfo
\$pinfo.FileName = "powershell"
\$pinfo.Arguments = "& '" + \$myinvocation.mycommand.definition + "'"
\$pinfo.Verb = "RunAs"
\$pinfo.RedirectStandardError = \$false
\$pinfo.RedirectStandardOutput = \$false
\$pinfo.UseShellExecute = \$true
\$p = New-Object System.Diagnostics.Process
\$p.StartInfo = \$pinfo
\$p.Start() | Out-Null
\$p.WaitForExit()
echo "* Child process finished"
type "C:/jenkins/transcript-${env.JOB_NAME}-${env.BUILD_NUMBER}.txt"
Remove-Item "C:/jenkins/transcript-${env.JOB_NAME}-${env.BUILD_NUMBER}.txt"
Exit \$p.ExitCode
} Else {
echo "Child process starting with admin privileges"
Start-Transcript -Path "C:/jenkins/transcript-${env.JOB_NAME}-${env.BUILD_NUMBER}.txt"
}
# put rest of your script here, it will get executed
# with elevated privileges.
"""
Even though this is an old thread, I still provide my methods here since I had the same problem, hoping to help anyone who is finding the answer.
First of all, This problem is not relevant to Jenkins, it's Windows's issue, you have to enable build-in Administrator to get an elevated privilege, here is the reference:
Administrator user
It is an unelevated administrator account
that is created by default during the installation of Windows. If an
administrator user tries to do something that requires elevated rights
(ex: run as administrator), Windows will display a UAC prompt for the
administrator user to approve before allowing the action.
Built-in "Administrator"
The hidden built-in elevated
"Administrator account" is a local account that has full
unrestricted access rights to the PC. By default, this "Administrator"
account will not be prompted by UAC.
After enabling build-in Administrator, you have two ways to elevate PS script which is triggered by Jenkins:
1.Login Windows with build-in Administrator:
This is the easiest way to achieve your goal, just log in with build-in Administrator, and everything are elevated, including the PS script triggered by Jenkins. (I am using this method.)
2.Pass credential and run as Administrator:
Add some codes in your PS script
$user = "Administrator"
$passwd = "password"
$securePasswd = ConvertTo-SecureString $passwd -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $user, $securePasswd
#Use Credential to prevent from being prompted for password
#Use argument -Verb RunAs to get script elevated
Start-Process powershell.exe -Credential $credential -ArgumentList "Start-Process powershell.exe -Verb RunAs -ArgumentList '-File hudson.ps1' -Wait"
Try this :
powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoExit -Command `\"cd \`\"%scriptFolderPath%`\"; & \`\".\%powershellScriptFileName%\`\"`\"\" -Verb RunAs"

How to run w32tm in non-elevated powershell

I am writing a helper script that will go through a list of servers and verify they are in sync with the NTP. The script shall be run as a normal script on request by the facility operator and shall request for Admin credentials if the target is not in sync. We unfortunately cannot change the NTP configuration at the moment so we have to make workaround.
What I have right now (and it works beautifully if the script is run as administrator) is a command ("w32tm /query /status" of a remote computer) that is executed via "Invoke-Command" so I can pass it Admin credentials.
My idea was to avoid using WinRM since the hostname resolution is not working properly in our system (it requires some painful host-to-IP-and-back-to-proper-hostname resolution) which makes the WinRM useless.
The command w32tm can obtain status of a remote computer but it needs to be run as administrator for it.
In both cases (run as administrator and run as normal user and later providing the credentials) the $script is executed as domain\administrator (confirmed with the check of Admin role and the "WhoAmI" command) but the status is only obtained when the whole script is executed as administrator.
For the execution as normal user I receive the error:
The following error occurred: Access is denied. (0x80070005)
All machines I use obviously allow remote execution since it works with administrator user.
So basically my question is why is the "w32tm ..." command not allowed in the $script if the role of the user is appropriate (it is administrator role) for the task?
The part of the script which I can't resolve:
function synchronize_remote_machine ($target, $username, $cred)
{
$script = {
param( [String] $compName )
$user = [Security.Principal.WindowsIdentity]::GetCurrent();
$userIsAdmin = (New-Object Security.Principal.WindowsPrincipal $user).`
IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
if (-not $userIsAdmin)
{
Write-Warning "You do not have Administrator rights to run this script!`n
Please re-run this script as an Administrator!"
}
else
{
whoAmI
w32tm /query /status /computer:$compName
#w32tm /resync /rediscover /computer:$compName
}
}
# resync via WinRM
try
{
#execute_resync_command $target $username $cred
if ($username -eq 'Administrator')
{
# when run as admin
invoke-command -ScriptBlock $script -ArgumentList $target;
}
else
{
# for normal user the initalized credential cals is used
invoke-command -computername "localhost" -Credential $cred -ScriptBlock $script -ArgumentList $target
}
}
catch
{
Write-Error "Error executing resync command on host $target."# -foregroundcolor "red"
throw
}
}
Rather than (re-)running the script with elevated privileges, I'd grant the operators group the SeSystemtimePrivilege on those servers. You can do that either with a group policy or by running ntrights.exe from the Server 2003 Resource Kit Tools on each server:
ntrights +r SeSystemtimePrivilege -u DOMAIN\operators
Even if you execute it as administrator, do to try to run you script in an elevated process ?
You can acheive that using Start-Process CmdLet.
start-process 'c:\system32\WindowsPowerShell\v1.0\powershell.exe' -verb runas -argumentlist "-file YourScript.ps1"

Running a command as Administrator using PowerShell?

You know how if you're the administrative user of a system and you can just right click say, a batch script and run it as Administrator without entering the administrator password?
I'm wondering how to do this with a PowerShell script. I do not want to have to enter my password; I just want to mimic the right-click Run As Administrator method.
Everything I read so far requires you to supply the administrator password.
If the current console is not elevated and the operation you're trying to do requires elevated privileges then you can start powershell with the Run as Administrator option :
PS> Start-Process powershell -Verb runAs
Microsoft Docs: Start-Process
Here is an addition to Shay Levi's suggestion (just add these lines at the beginning of a script):
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$arguments = "& '" +$myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
This results in the current script being passed to a new powershell process in Administrator mode (if current User has access to Administrator mode and the script is not launched as Administrator).
Self elevating PowerShell script
Windows 8.1 / PowerShell 4.0 +
One line :)
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 }
# Your script here
Benjamin Armstrong posted an excellent article about self-elevating PowerShell scripts. There a few minor issue with his code; a modified version based on fixes suggested in the comment is below.
Basically it gets the identity associated with the current process, checks whether it is an administrator, and if it isn't, creates a new PowerShell process with administrator privileges and terminates the old process.
# Get the ID and security principal of the current user account
$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent();
$myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID);
# Get the security principal for the administrator role
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator;
# Check to see if we are currently running as an administrator
if ($myWindowsPrincipal.IsInRole($adminRole))
{
# We are running as an administrator, so change the title and background colour to indicate this
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)";
$Host.UI.RawUI.BackgroundColor = "DarkBlue";
Clear-Host;
}
else {
# We are not running as an administrator, so relaunch as administrator
# Create a new process object that starts PowerShell
$newProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell";
# Specify the current script path and name as a parameter with added scope and support for scripts with spaces in it's path
$newProcess.Arguments = "& '" + $script:MyInvocation.MyCommand.Path + "'"
# Indicate that the process should be elevated
$newProcess.Verb = "runas";
# Start the new process
[System.Diagnostics.Process]::Start($newProcess);
# Exit from the current, unelevated, process
Exit;
}
# Run your code that needs to be elevated here...
Write-Host -NoNewLine "Press any key to continue...";
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown");
Here's a self-elevating snippet for Powershell scripts which preserves the working directory:
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
exit;
}
# Your script here
Preserving the working directory is important for scripts that perform path-relative operations. Almost all of the other answers do not preserve this path, which can cause unexpected errors in the rest of the script.
If you'd rather not use a self-elevating script/snippet, and instead just want an easy way to launch a script as adminstrator (eg. from the Explorer context-menu), see my other answer here: https://stackoverflow.com/a/57033941/2441655
You can create a batch file (*.bat) that runs your powershell script with administrative privileges when double-clicked. In this way, you do not need to change anything in your powershell script.To do this, create a batch file with the same name and location of your powershell script and then put the following content in it:
#echo off
set scriptFileName=%~n0
set scriptFolderPath=%~dp0
set powershellScriptFileName=%scriptFileName%.ps1
powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"%scriptFolderPath%`\"; & \`\".\%powershellScriptFileName%\`\"`\"\" -Verb RunAs"
That's it!
Here is the explanation:
Assuming your powershell script is in the path C:\Temp\ScriptTest.ps1, your batch file must have the path C:\Temp\ScriptTest.bat. When someone execute this batch file, the following steps will occur:
The cmd will execute the command
powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"C:\Temp\`\"; & \`\".\ScriptTest.ps1\`\"`\"\" -Verb RunAs"
A new powershell session will open and the following command will be executed:
Start-Process powershell "-ExecutionPolicy Bypass -NoProfile -NoExit -Command `"cd \`"C:\Temp\`"; & \`".\ScriptTest.ps1\`"`"" -Verb RunAs
Another new powershell session with administrative privileges will open in the system32 folder and the following arguments will be passed to it:
-ExecutionPolicy Bypass -NoProfile -NoExit -Command "cd \"C:\Temp\"; & \".\ScriptTest.ps1\""
The following command will be executed with administrative privileges:
cd "C:\Temp"; & ".\ScriptTest.ps1"
Once the script path and name arguments are double quoted, they can contain space or single quotation mark characters (').
The current folder will change from system32 to C:\Temp and the script ScriptTest.ps1 will be executed. Once the parameter -NoExit was passed, the window wont be closed, even if your powershell script throws some exception.
Using
#Requires -RunAsAdministrator
has not been stated, yet. It seems to be there only since PowerShell 4.0.
http://technet.microsoft.com/en-us/library/hh847765.aspx
When this switch parameter is added to your requires statement,
it specifies that the Windows PowerShell session in which you are
running the script must be started with elevated user rights
(Run as Administrator).
To me, this seems like a good way to go about this, but I'm not sure of the field experience, yet. PowerShell 3.0 runtimes probably ignore this, or even worse, give an error.
When the script is run as a non-administrator, the following error is given:
The script 'StackOverflow.ps1' cannot be run because it contains a
"#requires" statement for running as Administrator. The current
Windows PowerShell session is not running as Administrator. Start
Windows PowerShell by using the Run as Administrator option, and then
try running the script again.
+ CategoryInfo : PermissionDenied: (StackOverflow.ps1:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ScriptRequiresElevation
You can easily add some registry entries to get a "Run as administrator" context menu for .ps1 files:
New-Item -Path "Registry::HKEY_CLASSES_ROOT\Microsoft.PowershellScript.1\Shell\runas\command" `
-Force -Name '' -Value '"c:\windows\system32\windowspowershell\v1.0\powershell.exe" -noexit "%1"'
(updated to a simpler script from #Shay)
Basically at HKCR:\Microsoft.PowershellScript.1\Shell\runas\command set the default value to invoke the script using Powershell.
The code posted by Jonathan and Shay Levy did not work for me.
Please find the working code below:
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
#"No Administrative rights, it will display a popup window asking user for Admin rights"
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments
break
}
#"After user clicked Yes on the popup, your file will be reopened with Admin rights"
#"Put your code here"
You need to rerun the script with administrative privileges and check if the script was launched in that mode. Below I have written a script that has two functions: DoElevatedOperations and DoStandardOperations. You should place your code that requires admin rights into the first one and standard operations into the second. The IsRunAsAdmin variable is used to identify the admin mode.
My code is an simplified extract from the Microsoft script that is automatically generated when you create an app package for Windows Store apps.
param(
[switch]$IsRunAsAdmin = $false
)
# Get our script path
$ScriptPath = (Get-Variable MyInvocation).Value.MyCommand.Path
#
# Launches an elevated process running the current script to perform tasks
# that require administrative privileges. This function waits until the
# elevated process terminates.
#
function LaunchElevated
{
# Set up command line arguments to the elevated process
$RelaunchArgs = '-ExecutionPolicy Unrestricted -file "' + $ScriptPath + '" -IsRunAsAdmin'
# Launch the process and wait for it to finish
try
{
$AdminProcess = Start-Process "$PsHome\PowerShell.exe" -Verb RunAs -ArgumentList $RelaunchArgs -PassThru
}
catch
{
$Error[0] # Dump details about the last error
exit 1
}
# Wait until the elevated process terminates
while (!($AdminProcess.HasExited))
{
Start-Sleep -Seconds 2
}
}
function DoElevatedOperations
{
Write-Host "Do elevated operations"
}
function DoStandardOperations
{
Write-Host "Do standard operations"
LaunchElevated
}
#
# Main script entry point
#
if ($IsRunAsAdmin)
{
DoElevatedOperations
}
else
{
DoStandardOperations
}
Adding my 2 cents. My simple version based on net session which works all the time so far in Windows 7 / Windows 10. Why over complicate it?
if (!(net session)) {$path = "& '" + $myinvocation.mycommand.definition + "'" ; Start-Process powershell -Verb runAs -ArgumentList $path ; exit}
just add to the top of the script and it will run as administrator.
You can also force the application to open as administrator, if you have an administrator account, of course.
Locate the file, right click > properties > Shortcut > Advanced and check Run as Administrator
Then Click OK.
This behavior is by design. There are multiple layers of security since Microsoft really didn't want .ps1 files to be the latest email virus. Some people find this to be counter to the very notion of task automation, which is fair. The Vista+ security model is to "de-automate" things, thus making the user okay them.
However, I suspect if you launch powershell itself as elevated, it should be able to run batch files without requesting the password again until you close powershell.
A number of the answers here are close, but a little more work than needed.
Create a shortcut to your script and configure it to "Run as Administrator":
Create the shortcut.
Right-click shortcut and open Properties...
Edit Target from <script-path> to powershell <script-path>
Click Advanced... and enable Run as administrator
Here is how to run a elevated powershell command and collect its output form within a windows batch file in a single command(i.e not writing a ps1 powershell script).
powershell -Command 'Start-Process powershell -ArgumentList "-Command (Get-Process postgres | Select-Object Path | Select-Object -Index 0).Path | Out-File -encoding ASCII $env:TEMP\camp-postgres.tmp" -Verb RunAs'
Above you see i first launch a powershell with elevated prompt and then ask that to launch another powershell(sub shell) to run the command.
C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell is where the shortcut of PowerShell resides. It too still goes to a different location to invoke the actual 'exe' (%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe).
Since PowerShell is user-profile driven when permissions are concerned; if your username/profile has the permissions to do something then under that profile, in PowerShell you would generally be able to do it as well. That being said, it would make sense that you would alter the shortcut located under your user profile, for example, C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell.
Right-click and click properties. Click "Advanced" button under the "Shortcut" tab located right below the "Comments" text field adjacent to the right of two other buttons, "Open File Location" and "Change Icon", respectively.
Check the checkbox that reads, "Run as Administrator". Click OK, then Apply and OK. Once again right click the icon labeled 'Windows PowerShell' located in C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell and select "Pin to Start Menu/Taskbar".
Now whenever you click that icon, it will invoke the UAC for escalation. After selecting 'YES', you will notice the PowerShell console open and it will be labeled "Administrator" on the top of the screen.
To go a step further... you could right click that same icon shortcut in your profile location of Windows PowerShell and assign a keyboard shortcut that will do the exact same thing as if you clicked the recently added icon. So where it says "Shortcut Key" put in a keyboard key/button combination like: Ctrl + Alt + PP (for PowerShell). Click Apply and OK.
Now all you have to do is press that button combination you assigned and you will see UAC get invoked, and after you select 'YES' you will see a PowerShell console appear and "Administrator" displayed on the title bar.
I have found a way to do this...
Create a batch file to open your script:
#echo off
START "" "C:\Scripts\ScriptName.ps1"
Then create a shortcut, on your desktop say (right click New -> Shortcut).
Then paste this into the location:
C:\Windows\System32\runas.exe /savecred /user:*DOMAIN*\*ADMIN USERNAME* C:\Scripts\BatchFileName.bat
When first opening, you will have to enter your password once. This will then save it in the Windows credential manager.
After this you should then be able to run as administrator without having to enter a administrator username or password.
I am using the solution below. It handles stdout/stderr via transcript feature and passes exit code correctly to parent process. You need to adjust transcript path/filename.
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
echo "* Respawning PowerShell child process with elevated privileges"
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "powershell"
$pinfo.Arguments = "& '" + $myinvocation.mycommand.definition + "'"
$pinfo.Verb = "RunAs"
$pinfo.RedirectStandardError = $false
$pinfo.RedirectStandardOutput = $false
$pinfo.UseShellExecute = $true
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
echo "* Child process finished"
type "C:/jenkins/transcript.txt"
Remove-Item "C:/jenkins/transcript.txt"
Exit $p.ExitCode
} Else {
echo "Child process starting with admin privileges"
Start-Transcript -Path "C:/jenkins/transcript.txt"
}
# Rest of your script goes here, it will be executed with elevated privileges
Another simpler solution is that you may also right click on "C:\Windows\System32\cmd.exe" and choose "Run as Administrator" then you can run any app as administrator without providing any password.
The problem with the #pgk and #Andrew Odri's answers is when you have script parameters, specially when they are mandatory. You can solve this problem using the following approach:
The user right-clicks the .ps1 file and selects 'Run with PowerShell': ask him for the parameters through input boxes (this is a much better option than use the HelpMessage parameter attribute);
The user executes the script through the console: allow him to pass the desired parameters and let the console force him to inform the mandatory ones.
Here is how would be the code if the script had the ComputerName and Port mandatory parameters:
[CmdletBinding(DefaultParametersetName='RunWithPowerShellContextMenu')]
param (
[parameter(ParameterSetName='CallFromCommandLine')]
[switch] $CallFromCommandLine,
[parameter(Mandatory=$false, ParameterSetName='RunWithPowerShellContextMenu')]
[parameter(Mandatory=$true, ParameterSetName='CallFromCommandLine')]
[string] $ComputerName,
[parameter(Mandatory=$false, ParameterSetName='RunWithPowerShellContextMenu')]
[parameter(Mandatory=$true, ParameterSetName='CallFromCommandLine')]
[UInt16] $Port
)
function Assert-AdministrativePrivileges([bool] $CalledFromRunWithPowerShellMenu)
{
$isAdministrator = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if ($isAdministrator)
{
if (!$CalledFromRunWithPowerShellMenu -and !$CallFromCommandLine)
{
# Must call itself asking for obligatory parameters
& "$PSCommandPath" #script:PSBoundParameters -CallFromCommandLine
Exit
}
}
else
{
if (!$CalledFromRunWithPowerShellMenu -and !$CallFromCommandLine)
{
$serializedParams = [Management.Automation.PSSerializer]::Serialize($script:PSBoundParameters)
$scriptStr = #"
`$serializedParams = '$($serializedParams -replace "'", "''")'
`$params = [Management.Automation.PSSerializer]::Deserialize(`$serializedParams)
& "$PSCommandPath" #params -CallFromCommandLine
"#
$scriptBytes = [System.Text.Encoding]::Unicode.GetBytes($scriptStr)
$encodedCommand = [Convert]::ToBase64String($scriptBytes)
# If this script is called from another one, the execution flow must wait for this script to finish.
Start-Process -FilePath 'powershell' -ArgumentList "-ExecutionPolicy Bypass -NoProfile -EncodedCommand $encodedCommand" -Verb 'RunAs' -Wait
}
else
{
# When you use the "Run with PowerShell" feature, the Windows PowerShell console window appears only briefly.
# The NoExit option makes the window stay visible, so the user can see the script result.
Start-Process -FilePath 'powershell' -ArgumentList "-ExecutionPolicy Bypass -NoProfile -NoExit -File ""$PSCommandPath""" -Verb 'RunAs'
}
Exit
}
}
function Get-UserParameters()
{
[string] $script:ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Enter a computer name:', 'Testing Network Connection')
if ($script:ComputerName -eq '')
{
throw 'The computer name is required.'
}
[string] $inputPort = [Microsoft.VisualBasic.Interaction]::InputBox('Enter a TCP port:', 'Testing Network Connection')
if ($inputPort -ne '')
{
if (-not [UInt16]::TryParse($inputPort, [ref]$script:Port))
{
throw "The value '$inputPort' is invalid for a port number."
}
}
else
{
throw 'The TCP port is required.'
}
}
# $MyInvocation.Line is empty in the second script execution, when a new powershell session
# is started for this script via Start-Process with the -File option.
$calledFromRunWithPowerShellMenu = $MyInvocation.Line -eq '' -or $MyInvocation.Line.StartsWith('if((Get-ExecutionPolicy')
Assert-AdministrativePrivileges $calledFromRunWithPowerShellMenu
# Necessary for InputBox
[System.Reflection.Assembly]::Load('Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') | Out-Null
if ($calledFromRunWithPowerShellMenu)
{
Get-UserParameters
}
# ... script code
Test-NetConnection -ComputerName $ComputerName -Port $Port
I recently needed this to build an environment on ansible. I say right away - the decision is not mine, but I don’t remember where I got it. Looks like that:
powershell.exe -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -Command Get-Service -Name ssh-agent | Set-Service -StartupType Automatic' -Verb RunAs}";
This example enables ssh-agent autostart.
The required command is specified after -Command. The only problem is the launch happens on a new PS instance, but so far this is the only way that I know to execute the command as an admin without additional steps.
The most reliable way I've found is to wrap it in a self-elevating .bat file:
#echo off
NET SESSION 1>NUL 2>NUL
IF %ERRORLEVEL% EQU 0 GOTO ADMINTASKS
CD %~dp0
MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 0); close();"
EXIT
:ADMINTASKS
powershell -file "c:\users\joecoder\scripts\admin_tasks.ps1"
EXIT
The .bat checks if you're already admin and relaunches the script as Administrator if needed. It also prevents extraneous "cmd" windows from opening with the 4th parameter of ShellExecute() set to 0.
On top of Shay Levy's answer, follow the below setup (just once)
Start a PowerShell with Administrator rights.
Follow Stack Overflow question PowerShell says “execution of scripts is disabled on this system.”.
Put your .ps1 file in any of the PATH folders, for example. Windows\System32 folder
After the setup:
Press Win + R
Invoke powershell Start-Process powershell -Verb runAs <ps1_file>
You can now run everything in just one command line. The above works on Windows 8 Basic 64-bit.
I haven't seen my own way of doing it before, so, try this out. It is way easier to follow and has a much smaller footprint:
if([bool]([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -notcontains "S-1-5-32-544") {
Start Powershell -ArgumentList "& '$MyInvocation.MyCommand.Path'" -Verb runas
}
Very simply, if the current Powershell session was called with administrator privileges, the Administrator Group well-known SID will show up in the Groups when you grab the current identity. Even if the account is a member of that group, the SID won't show up unless the process was invoked with elevated credentials.
Nearly all of these answers are a variation on Microsoft's Ben Armstrong's immensely popular method of how to accomplish it while not really grasping what it is actually doing and how else to emulate the same routine.
To append the output of the command to a text filename which includes the current date you can do something like this:
$winupdfile = 'Windows-Update-' + $(get-date -f MM-dd-yyyy) + '.txt'
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -Command `"Get-WUInstall -AcceptAll | Out-File $env:USERPROFILE\$winupdfile -Append`"" -Verb RunAs; exit } else { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -Command `"Get-WUInstall -AcceptAll | Out-File $env:USERPROFILE\$winupdfile -Append`""; exit }
This is a clarification ...
The powershell RUNAS / SAVECRED credential "is not safe", tried it and it adds the admin identity and password into the credential cache and can be used elsewhere OOPS!. If you have done this I suggest you check and remove the entry.
Review your program or code because the Microsoft policy is you cannot have mixed user and admin code in the same code blob without the UAC (the entry point) to execute the program as admin. This would be sudo (same thing) on Linux.
The UAC has 3 types, dont'see, a prompt or an entry point generated in the manifest of the program. It does not elevate the program so if there is no UAC and it needs admin it will fail. The UAC though as an administrator requirement is good, it prevents code execution without authentication and prevents the mixed codes scenario executing at user level.
Elevated PowerShell from Start>Run
You cannot run elevated powershell from the "run" command, in 2012R2 or 2016, without shelling twice:
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell -Command "saps PowerShell -Verb RunAs "
It turns out it was too easy. All you have to do is run a cmd as administrator. Then type explorer.exe and hit enter. That opens up Windows Explorer.
Now right click on your PowerShell script that you want to run, choose "run with PowerShell" which will launch it in PowerShell in administrator mode.
It may ask you to enable the policy to run, type Y and hit enter. Now the script will run in PowerShell as administrator. In case it runs all red, that means your policy didn't take affect yet. Then try again and it should work fine.