Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 953 Vote(s) - 3.49 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Running a command as Administrator using PowerShell?

#11
On top of Shay Levy's answer, follow the below setup (just once)

1. Start a PowerShell with Administrator rights.
2. Follow Stack Overflow question *[PowerShell says “execution of scripts is disabled on this system.”][1]*.
2. Put your .ps1 file in any of the `PATH` folders, for example. Windows\System32 folder

After the setup:

1. Press <kbd>Win</kbd> + <kbd>R</kbd>
2. 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.

[1]:

[To see links please register here]

Reply

#12
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.
Reply

#13
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 }
Reply

#14
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`.
Reply

#15
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.
Reply

#16
The problem with the [@pgk][1] and [@Andrew Odri][2]'s answers is when you have script parameters, specially when they are mandatory. You can solve this problem using the following approach:

1. 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);
2. 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

[1]:

[To see links please register here]

[2]:

[To see links please register here]

Reply

#17
Using

`#Requires -RunAsAdministrator`

has not been stated, yet. It seems to be there only since PowerShell 4.0.

[To see links please register here]


>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

Reply

#18
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 <kbd>Advanced...</kbd> and enable `Run as administrator`
Reply

#19
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
Reply

#20
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.


Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through