How to execute a powershell with '-command' argument in administration mode - powershell

How can I run a powershell with -command parameters?
I tried adding '-Verb runAs', but I get a null valued expression.
powershell -Verb runAs -command "(Get-Date (Get-Process explorer).StartTime).ToString('yyyyMMdd')"
I open a powershell with admin right, the command
(Get-Date (Get-Process explorer).StartTime).ToString('yyyyMMdd')
return a right value. But when I start a powershell without admin right, I get a null value.
So I think the problem is the 'powershell -Verb runAs' does not run the command in admin mode.
Note: I logged in as ad administer when I tried this.

So elevating PowerShell's process can be done from within a script if you don't mind running a script instead of just executing a command. This will check if the process is already elevated, and if not it will re-launch the process with the RunAs verb so that it's running with elevated rights.
# Elevate UAC if not already running As Administrator
# 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 Administrator"
if (!$myWindowsPrincipal.IsInRole($adminRole))
{
# We are not running "as Administrator" - so relaunch as administrator
# Create an encoded string to re-launch the script bypassing execution policy
$Code = ". '$($myInvocation.MyCommand.Definition)'"
$Encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($code))
# Indicate that the process should be elevated
Start-Process PowerShell.exe -Verb RunAs -ArgumentList "-EncodedCommand",$Encoded
# Exit from the current, unelevated, process
exit
}
# End UACElevation
The code is a little convoluted with the encrypting of the command and what not, but I found that I sometimes had issues with execution policy blocking me if I didn't do it this way. This avoids execution policy blocking PowerShell from running scripts, since it technically isn't running a script, just an encoded command. That command just happens to be for it to run a script once the PSSession is started.

Related

How to run an application from powershell without elevated rights

I have a powershell script that needs to be run as admin to set IP addresses. Then I need to run an application as non-admin. As I understand it, this corresponds to the term "elevated rights".
If I simply double click the .exe from the file explorer (not "run as admin"), the app runs as intended without elevated rights.
I have found several tips online on how to accomplish this, however I haven't succeeded with the following commands in my script:
(from How to run exe with/without elevated privileges from PowerShell)
runas /trustlevel:0x20000 "\..\myApp.exe":
this results in an "Internal error" because access is denied to a certain ".lock" file related to an eclipse workspace.
Second approach:
Start-Process -filepath "\..\myApp.exe" -ArgumentsList "-ExecutionPolicy bypass -Scope CurrentUser"
this runs the application but it's run in elevated state.
EDIT: Third approach:
I tried making a second script from where I run
Start-Process -FilePath "\..\myApp.exe"
which I call from my main script using:
Start-Process PowerShell -ArgumentList '-File ""\..\mySecondScript.ps1""' -Verb open
This results in myApp running with elevated rights when its called from within the main script, but without elevated rights when run on powershell on its own.

How can I bypass execution policy when running scripts from Powershell ISE

So I can write a script in Powershell ISE, not save it, and it will run (F5/green arrow on the ISE). Once I save it, I get the error saying I can't run saved scripts. If I open a Powershell window in the directory the saved script exists, I can run it with
powershell -ExecutionPolicy ByPass -File script.ps1
But is there a way I can get this to work when running it via the ISE's green arrow/F5? I don't have admin access to this PC
Edit: Windows 10
Ok so I just found out you can set Execution Policy for yourself (current user) without having admin rights. So if you're coming here from google do this:
Set-ExecutionPolicy -Scope "CurrentUser" -ExecutionPolicy "RemoteSigned"
Also you can run individual script without setting Execution Policy for current user, by passing Execution Policy only for file script.
For example:
Powershell -executionpolicy RemoteSigned -File "C:\scripts\script.ps1"
Very convenient for scheduled tasks in the Windows Task Scheduler to run PowerShell commands (scripts).
That's my addition for google users

run another power shell script in elevated mode as administrator

I am currently logged into my system as administrator, and run power1.ps1 code to call another power2.ps1 script in elevated mode.
$command = "C:\script\Power2.ps1"
Invoke-Expression $command
power2.ps1 includes the block to run the script with admin privileges, but my problem is I that I get a UAC pop-up dialog asking for confirmation where I have to click on Yes.
Code in Power2.ps1
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
}
Write-Host "Admin Privilege Code Here"
Is there any way I can completely automate the process? I will not be able to change the UAC access to disable.
Trying to simulate a user's response to a UAC (User Account Control) dialog shouldn't be done - because it defeats the entire purpose of UAC - and most likely cannot be done (if it could be done, that would be a serious bug exploitable by malware and is certainly not something to rely upon; similarly, while it is possible to disable UAC altogether (which itself requires administrative privileges), doing so is strongly discouraged for security reasons).
However, with limitations you can use a scheduled task to bypass UAC for a given command, by calling that scheduled task on demand:
Create an auxiliary scheduled task that invokes your Power2.ps1 script and is configured to run elevated.
In the Task Scheduler (taskschd.msc) UI that means: Run with highest privilege must be checked (tab General) and also Allow task to be run on demand (tab Settings).
The task must be configured to run in the same user account that it will be on-demand invoked from, and that user account must be a member of the Administrators group.
Use Start-ScheduledTask <task-path> (or schtasks.exe /Run /TN <task-path>) to invoke this task on demand, from the same account that the task is configured for, as noted.
Start-ScheduledTask (as well as schtasks.exe /Run) runs asynchronously, so for synchronous invocation more work is needed - see this article.
Note that using -AsJob to return a job whose completion can be waited for with Wait-Job unfortunately appears not to help (as of Windows PowerShell 5.1 / PowerShell 7.2.1): the job is reported as completed before the task's command has terminated.
Also, the task's command invariably runs in a new console window (if the executable invoked is a console application).

Using powershell script to kill process but access deined

I need using powershell script to kill a process, however access denied. How can I get admin with powershell script? In addition, I do not want to input Admin account and password manually. The Get-Admin process needs to be done automatically. What am I suppose to do?
You would need to elivate your script, or console prompt, to use the "run as administrator" option. A good example script can be found here on how you might do this in your script.
The meat of the script provided in the link just takes the user running the script and verify if the current session is elavated. If it is not you have to open one up as that in order to kill a process. You would also deal with UAC if you are on Windows, that if the user running it does not have local admin rights you will be prompted to enter credentials.
Snippet of the code that verifies if the execution account is admin:
# 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
$myWindowsPrincipal.IsInRole($adminRole)
You can find a few other options to get elevated permissions here.
Just do
start-process pwsh -Verb RunAs
or
start-process powershell -Verb RunAs
to get yourself an elevated shell. Then run the command you want

How to run exe with/without elevated privileges from PowerShell

I would like an easy way to run a process with different privileges from the same user without asking or knowing his/her password. A dialog is okay if necessary. I would prefer not to launch a PowerShell sub-process to accomplish this.
Scenario 1:
PowerShell script is running in admin-mode. I want to launch a script or an .exe without admin privileges but on the same user.
Scenario 2:
PowerShell script is running in normal mode. I want to launch a script or an .exe with admin privileges on the same user.
Let's split this into three parts.
First determine if current session is running with admin privileges:
$CurrentID = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$CurrentPrincipal = new-object System.Security.Principal.WindowsPrincipal($CurrentID)
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
# Check to see if session is currently with admin privileges
if ($CurrentPrincipal.IsInRole($adminRole)) {
write-host "Yes we are running elevated."
}else{
write-host "No this is a normal user session."
}
Now, if we are running with or without elevation, you can start a new process with elevated privileges like this:
$newProc = new-object System.Diagnostics.ProcessStartInfo "PowerShell"
# Specify what to run
$newProc.Arguments = "powershell.exe"
# If you set this, process will be elevated
$newProc.Verb = "runas"
[System.Diagnostics.Process]::Start($newProc)
And lastly, if we have elevated privileges, but would like to start a new process without...
I have no idea. Will have to try to find the answer to this, but as it is not a common scenario, I had no luck so far.
EDIT: I have now seen a couple of “solutions” for this scenario. There is no native way to do this in .NET/PowerShell. Some are quite complicated (Calls to some 12 COM objects). This vista-7-uac-how-to-lower-process-privileges is a good reference.
The one that seems most elegant to me, is exploiting a “bug” in explorer.exe.
Just launch you .exe using explorer.exe and the resulting process runs without privilege elevation again.
$newProc = new-object System.Diagnostics.ProcessStartInfo "PowerShell"
# Specify what to run, you need the full path after explorer.exe
$newProc.Arguments = "explorer.exe C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
[System.Diagnostics.Process]::Start($newProc)
EDIT #2: Another way I have just found to start a new non-elevated process from an already elevated environment is to use the runas.exe with the 0x20000 (Basic User) trust level:
C:\> runas /showtrustlevels
The following trust levels are available on your system:
0x20000 (Basic User)
C:\> runas /trustlevel:0x20000 devenv
I use this as first command in all scripts that requires elevated mode, it transfer the script to another elevated process if I forgot to start up as Admin. You have to confirm so it's not suitable for automated tasks
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 }