Run Powershell with arguments via CMD - powershell

I have the following .BAT script that basically calls Powershell and it works fine.
CMD /C PowerShell "SL -PSPath '%CD%'; $Path = (GL).Path; SL ~; Start PowerShell -Verb RunAs -Args \"-ExecutionPolicy ByPass" SL -PSPath '"$Path"'; & '".\RDPSwitchToConsle.ps1"'"\""
I'm trying to extend it to add more arguments, specifically -WindowStyle Hidden.
I've tried a couple of things, but can't get the script .BAT to run. It just opens Powershell straight away and closes immediately, which is a sign that the arguments/parameters are not loaded correctly due to incorrect structure.
I've tried adding the argument like this:
CMD /C PowerShell "SL -PSPath '%CD%'; $Path = (GL).Path; SL ~; Start PowerShell -Verb RunAs -Args \"-ExecutionPolicy ByPass -WindowStyle Hidden" SL -PSPath '"$Path"'; & '".\RDPSwitchToConsle.ps1"'"\""

Apply -WindowStyle Hidden to the Start-Process (start) call, not to the nested powershell.exe call.
Here's a simplified version of your command:
PowerShell "SL ~; Start -WindowStyle Hidden -Verb RunAs PowerShell \"-ExecutionPolicy ByPass SL -PSPath '%CD%'; ^& .\RDPSwitchToConsle.ps1\""

Related

Run Powershell 7 from CMD

I have a .bat script that runs Powershell as Admin and then runs a Powershell script in the same folder as the .bat file. This works perfectly fine:
CMD /C powershell "Set-Location -PSPath '%CD%'; $Path =
(Get-Location).Path; Set-Location ~; Start powershell -Verb RunAs -Args
"-ExecutionPolicy ByPass" Set-Location -PSPath '"$Path"'; &
'".\Start_TOW_VM.ps1"'"""
I am now trying to use Powershell 7 (pwsh) instead and I thought it'd be as simple as changing to this:
CMD /C pwsh "Set-Location -PSPath '%CD%'; $Path = (Get-Location).Path;
Set-Location ~; Start pwsh -Verb RunAs -Args "-ExecutionPolicy
ByPass" Set-Location -PSPath '"$Path"'; & '".\Start_TOW_VM.ps1"'"""
Unfortunately, it doesn't work and complains about the Set-Location command, even though that command works perfectly fine in Powershell 7. What am I doing wrong here?
Figured it out, here's the solution:
CMD /C pwsh -c Set-Location -PSPath '%CD%'; $Path =
(Get-Location).Path; Set-Location ~;write-host $path; start pwsh -Verb
RunAs "-command Set-ExecutionPolicy ByPass;
Set-Location -PSPath '"$Path"'; & '".\Start_TOW_VM.ps1"'"
Simply needed to add -command inside the escaped ".

How do I run a PowerShell script as administrator using a shortcut?

I'm trying to run a PowerShell script as administrator using a shortcut. I have tried many ways, but it still does not work:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -NoExit -Verb RunAs Start-Process powershell.exe -ArgumentList '-file C:\project\test.ps1'
With this command, it will create two PowerShell windows and one window will close.
I also tried this one:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -NoExit Start-Process powershell.exe -Verb RunAs -File 'C:\project\test.ps1'
Can some one please help?
Tl;dr
This will do the trick:
powershell.exe -Command "& {$wd = Get-Location; Start-Process powershell.exe -Verb RunAs -ArgumentList \"-ExecutionPolicy ByPass -NoExit -Command Set-Location $wd; C:\project\test.ps1\"}"
Explanation
First, you have to call PowerShell to be able to execute Start-Process. You don't need any additional paramters at this point, because you just use this first PowerShell to launch another one. You do it like this:
powershell.exe -Command "& {...}"
Inside the curly braces you can insert any script block. First you will retrieve your current working directory (CWD) to set it in the new launched PowerShell. Then you call PowerShell with Start-Process and add the -Verb RunAs parameter to elevate it:
$wd = Get-Location; Start-Process powershell.exe -Verb RunAs -ArgumentList ...
Then you need to add all desired PowerShell parameters to the ArgumentList. In your case, these will be:
-ExecutionPolicy ByPass -NoExit -Command ...
Finally, you pass the commands that you want to execute to the -Command parameter. Basically, you want to call your script file. But before doing so, you will set your CWD to the previously retrieved directory and THEN call your script:
Set-Location $wd; C:\project\test.ps1
In total:
powershell.exe -Command "& {$wd = Get-Location; Start-Process powershell.exe -Verb RunAs -ArgumentList \"-ExecutionPolicy ByPass -NoExit -Command Set-Location $wd; C:\project\test.ps1\"}"

How do I call an elevated PowerShell from Windows command prompt to execute commands and a PowerShell script file?

The following script works fine in Powershell:
Set-ExecutionPolicy Bypass -Scope Process -Force; Invoke-Webrequest
'https://blah.blob.core.windows.net/laps/AutoAutoPilot.ps1' -OutFile
C:\script.ps1; C:\script.ps1
I'm trying to convert it so that it runs as a CMD/BAT file. I simply need to double click to run it. I need the CMD/BAT file to run Powershell as administrator and from there, it will run the script from above. Here's what I have. It'll just quit straight away without doing anything.
powershell -ExecutionPolicy Bypass -c Start-Process -Verb RunAs -Wait
powershell.exe '-ExecutionPolicy Bypass -Noexit -c Set-Location
"\"\\\"%CD%\\\"\""; -c "& Invoke-Webrequest
\"https://blah.blob.core.windows.net/laps/AutoAutoPilot.ps1\"
-OutFile C:\script.ps1; C:\script.ps1" '
Update:
I got it working now. The full output looks like this:
powershell -Command "& ({Start-Process powershell -Verb RunAs -ArgumentList '-ExecutionPolicy Bypass -NoExit -Command Invoke-WebRequest -Uri https://blah.blob.core.windows.net/laps/AutoAutoPilot.ps1 -OutFile C:\script.ps1; C:\script.ps1'})"
If you use the -NoExit parameter when starting powershell.exe PowerShell should not close after the script has finished running. Afterwards if you do not see errors, you can look at the $error variable, to see any errors which occurred when running your script.
You are trying to run your PowerShell code, using PowerShell.exe from command prompt, so you should be able to use the same code as you did before, when you were running your code directly in PowerShell before.
To my understanding you want to run powershell code in a batch-file.well Depending upon your preference there are multiple solutions to this problem(well i haven't checked any of them):
Solution:1
make a batch file and give your powershell script to it as a parameter.
Without Admin access:
#ECHO OFF
PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "& '%~dpn0.ps1'"
PAUSE
With Admin access:
#ECHO OFF
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -Verb RunAs}"
PAUSE
Solution:2
If you don't want an external .ps1 file,then you can try this.just save it as something.bat
powershell -command if ($true)^
Set-ExecutionPolicy Bypass -Scope Process -Force; Invoke-Webrequest 'https://blah.blob.core.windows.net/laps/AutoAutoPilot.ps1' -OutFile C:\script.ps1; C:\script.ps1^
This should do the trick:
powershell -Command "& {Start-Process powershell -Verb RunAs -ArgumentList '-ExecutionPolicy Bypass -NoExit -Command Set-Location -Path C:\whatever\working\directory\you\need; Invoke-WebRequest -Uri https://blah.blob.core.windows.net/laps/AutoAutoPilot.ps1 -OutFile C:\script.ps1; C:\script.ps1'}"
Explanation:
When executing commands in PowerShell using the -Command argument, ExecutionPolicies do not apply as your are executing a single command and not a script. Even the execution of a scriptblock consisting of multiple commands counts as the execution of a single command. That's why you can directly call PowerShell from the command prompt like this (without anything else):
powershell -Command ...
-Command expects - to read from stdin or a scriptblock (read more). Scriptblocks have to be enclosed in curly braces ({...}). If you pass a scriptblock from the command prompt to PowerShell, you also have to add the call operator &:
powershell -Command "& {...}"
As you need an elevated PowerShell, you start a new PowerShell process from the previous PowerShell with Start-Process in combination with the -Verb RunAs argument. You add all arguments that you want to pass to the elevated PowerShell to the -ArgumentList argument:
... Start-Process powershell -Verb RunAs -ArgumentList '...' ...
As you want to call a script file, you now need the corresponding ExecutionPolicy. If you don't want to change it on the system, you can bypass the ExecutionPolicy with -ExecutionPolicy Bypass as you already did. And you also add -NoExit here. To pass your desired PowerShell commands, you use the -Command argument again. This time, you don't need the call operator and you can also omit the curly braces as we are now in PowerShell and not in the command prompt anymore.
... -ExecutionPolicy Bypass -NoExit -Command Set-Location -Path C:\whatever\working\directory\you\need; Invoke-WebRequest -Uri https://blah.blob.core.windows.net/laps/AutoAutoPilot.ps1 -OutFile C:\script.ps1; C:\script.ps1 ...

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?

Starting an admin shell then executing multiple commands

I have a powershell script and a bat file that launches it. I want the bat file to open powershell, then have powershell start another shell with elevated privileges, then run two commands. First command is change directory, second command is start a powershell script.
So far I have this:
powershell -NoProfile -ExecutionPolicy ByPass -Command "& {Start-Process PowerShell -Verb RunAs -ArgumentList '-NoExit -NoProfile -ExecutionPolicy Bypass cd %~dp0 .\App\Deploy-Application.ps1}'"
This is the section I'm having problems with:
cd %~dp0 .\App\Deploy-Application.ps1
I want to run these two commands but I'm not sure how. It runs a single command. I tried adding a semicolon between the commands but it didn't work.
Made a quick test and this is what i got working:
Test.bat
cd %~dp0
powershell -NoProfile -Command ".\test.ps1"
Test.ps1
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$arguments = "-noprofile & '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
Write-Host "Rawr"
Pause
If i run the batch file, it opens the powershell script that then checks if the current window is being run as an administrator and if not, reopens the script as an administrator.
After which it displays Rawr on my screen.
In your case instead of the Write-Host you could put
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$arguments = "-noprofile & '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
cd <Your directory to change to here>
<run command here>
Pause