Powershell RunAs Administrator - powershell

I have the script bellow which I would like to have run itself as Administrator without using a batch file.
The issue is that when I run the script, it opens a new administrator window and then just closes immediately.
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
}
Get-AppxProvisionedPackage -Online | Sort-Object -Property DisplayName | Select-Object -Property DisplayName

Add -NoExit to the PowerShell command line (otherwise, when given a script, it exits when that script has completed).

Add the -noexit to the argumentlist that launches your elevated process.

Related

Switch service running state using powershell (using UAC prompts)

$serviceName = "wsearch"
$isRunning = Get-Service | Where-Object {$_.Status -eq "Running" -and $_.Name -eq $serviceName}
$isStopped = Get-Service | Where-Object {$_.Status -eq "Stopped" -and $_.Name -eq $serviceName}
if ($isStopped) {
Start-Service -InputObject $isStopped
Start-Sleep -s 10
}
if ($isRunning) {
Stop-Service -InputObject $isRunning
Start-Sleep -s 10
}
I want to run this script, but I don't want to set Administrator execution policy (which is set to max restrictive), while regular user policy is lax.
I want to run the script as a regular user and trigger the UAC prompt for each command (akin to -Verb RunAs), however, Start-Service does not accept this parameter.
I guess I can run a Start-Process "sc" but that defeats the purpose of powershell.
The ultimate goal of the script is to swtich the state of a service based on the current running state.
There is no way to run one-off commands elevated (as admin) in a non-elevated powershell session. This would be similar to 'sudo' in Linux which just doesn't exist in the Windows world. Instead you could use something like the following to start a powershell session as administrator and run the commands there. You are not limited to calling 'sc'
Start-Process -Verb RunAs -FilePath 'powershell' -Arguments '-Command <your commands>'
To run a powershell script with elevated privileges you could substitute -Command for -File (but -Command <path to file> will also work)
Start-Process -Verb RunAs -FilePath 'powershell' -Arguments '-File <path to script>'

Powershell-Command to download a file with admin rights

I try do download a file via a powershell command. The command I use is simple:
Start-BitsTransfer -Source 'https://download.com/file.zip' -Destination 'E:\test\file.zip'
I can run the command in PS succesfully. But now I want to run it with elevated rights. So I gooogled and found this solution:
There it says the command should be:
Start-Process powershell.exe -Verb Runas -ArgumentList "-Command & {get-process}"
So I tried adjusting it for my use case:
Start-Process powershell.exe -Verb Runas -ArgumentList "-Command & {Start-BitsTransfer -Source 'https://download.com/file.zip' -Destination 'E:\test\file.zip'}"
But all is does is open a new PS-Window and closing it right after. Where is my mistake?
You can change to this
Start-Process powershell.exe -Verb Runas -ArgumentList "& {Start-BitsTransfer -Source 'https://download.com/file.zip' -Destination 'E:\test\file.zip'}"
Note the window will close after the execution completes. If you would like to see the output/errors (such as what would be shown in your non working example) just add another command to pause.
Start-Process powershell.exe -Verb Runas -ArgumentList "& {Start-BitsTransfer -Source 'https://download.com/file.zip' -Destination 'E:\test\file.zip';pause}"
& is used to invoke a command. It's useful for executing strings or scriptblocks. It runs in a child runspace.
& 'Get-Host'
& 'Write-Host' Hello -Fore Green
& {Write-Host Goodbye -Fore Cyan}
; is used to separate different commands on the same line.
& {$name = 'Doug';Write-Host Hello $name}
You can also use a period to invoke a scriptblock in the current runspace. In the previous command the $name variable would be empty in the callers scope where the following command would leave the variable defined.
& {$name = 'Doug';Write-Host Hello $name}
$name # empty as it all happens in the child scope
vs
. {$name = 'Doug';Write-Host Hello $name}
$name # populated because it's brought into the caller's scope

Run powershell commands from cmd / batch

I would like to run the following as administrator:
PowerShell -NoProfile -ExecutionPolicy Unrestricted -Command
.\Get-WindowsAutoPilotInfo.ps1 -ComputerName $env:computername
-OutputFile .\computers.csv -append
I would like to simply double click on a .cmd or .bat file and have it invoke the Powershell script as administrator. Here's what I have:
PowerShell "SL -PSPath '%CD%'; $Path = (GL).Path; SL ~; Start
PowerShell -Verb RunAs -Args \"-ExecutionPolicy Unrestricted -Noexit"
SL -PSPath '"$Path"'; & '".\UninstallBloatware.ps1" "-ComputerName
$env:computername" "-OutputFile .\computers.csv" "-append"' "\""
I copied most of the code above from somewhere I can't remember. I don't know enough about quotes structure to know how to fix this. Any ideas what I'm doing wrong?

Run a powershell script on a remote system with elevated permissions to enable remoting

I am trying to use the following code to copy a PowerShell script to remote windows 7 machine; run it with elevated privileges on this machine to enable remoting on that system.
It is copying the script file to the remote system but it is not executing the command in the remote PowerShell session because of the empty $command variable (the second line in the script below is not working).
Copy-Item -Path C:\users\user1\Myscript.ps1 -Destination \\some-computer\c$\Myscript.ps1
$command = PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\Myscript.ps1""' -Verb RunAs > C:\PS-result1.txt}"
$cmd = "CMD.EXE /c "+$command
Invoke-WmiMethod -class Win32_process -name Create -ArgumentList $cmd -ComputerName "some-computer"
Start-Sleep -s 8
Get-Content \\some-computer\C$\PS-result1.txt
Is it possible to accomplish this?
Thanks,
Using WMI to call CMD to call PowerShell to call Start-Process to call PowerShell again? That seems a little complicated.
Try something much simpler:
$command = "PowerShell.exe ""C:\Myscript.ps1"" > ""C:\PS-result1.txt"""
Invoke-WmiMethod -class Win32_process -name Create -ArgumentList $command -ComputerName "some-computer"

Powershell running as a another user with elevated privileges

I have two scripts located in C:\setup: script.ps1 and script1.ps1.
I want to be able to run the script1.ps1 from withing script.ps1 as another user and with elevated privileges but I cannot make it work. The new powershell window opens but closes immediately ...
here is the script:
$cspath = $MyInvocation.MyCommand.Path
$sfolder = Split-Path $cspath
$spath = Join-Path $sfolder "\Script1.ps1"
$sa = "domain\user"
$sap = "userpassword"
$sasp = ConvertTo-SecureString -String $sap -AsPlainText -Force
$sac = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $sa, $sasp
Start-Process $PSHOME\powershell.exe `
-Credential $sac `
-ArgumentList "-Command Start-Process $PSHOME\powershell.exe -ArgumentList `"'$spath'`" -Verb Runas" -Wait
Any help will be appreciated ...
It looks like you might need to adjust your parameters for powershell.exe. Instead of using -ArgumentList, which I don't think is valid, you should use the -File parameter. Also, you will want to use the -ExecutionPolicy Bypass parameter to ensure that the script execution policy is not interfering.
Finally, I would recommend removing the single quotes from around the script path, as the Windows command interpreter does not understand single quotes to surround parameters.
Give this a try:
$ArgumentList = '-Command Start-Process -FilePath $PSHOME\powershell.exe -ArgumentList "-ExecutionPolicy Bypass -File \"{0}\"" -Verb Runas' -f $sPath;
Start-Process $PSHOME\powershell.exe `
-Credential $sac `
-ArgumentList $ArgumentList -Wait
Update
It seems that some quoting rules were at play here as well, since we are embedding one command inside of another. I wrote and tested a fully function script on PowerShell v4.0.
Here are the contents:
# Create test directory and script file
[void](New-Item -Path c:\test -ItemType Directory -Force);
Set-Content -Path c:\test\test1.ps1 -Value 'Add-Content -Path $PSScriptRoot\blah.txt -Value (Get-Date);';
# Get credential and define script path
$Credential = Get-Credential;
$ScriptPath = 'c:\test\test1.ps1';
# Define the command line arguments
$ArgumentList = 'Start-Process -FilePath powershell.exe -ArgumentList \"-ExecutionPolicy Bypass -File "{0}"\" -Verb Runas' -f $ScriptPath;
Start-Process -FilePath powershell.exe `
-Credential $Credential `
-ArgumentList $ArgumentList -Wait -NoNewWindow;
I can confirm that I get a UAC prompt, and the target script successfully executes.
Since you're concerned about the new session window closing, I'm guessing you want command line output.
Start-Process is working as intended. It will run the script passed in through -ArgumentList and exit the session. This means it will not hold to display command line output - the session will terminate immediately after the process completes.
If you want a persistent session, use New-PSSession. Otherwise, you could export the data you're gathering to a file.