Run powershell commands from cmd / batch - powershell

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?

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 ".

Run Powershell with arguments via CMD

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\""

How to Run Long Powershell script from Windows Command Prompt (CMD)

I tried to launch a long powershell script with the name "long name here.ps1" from command prompt. But I am also trying to ensure that it runs as an administrator command in powershell. I have all execution policies in powershell set accordingly I used the ss64 set-executionpolicy command guide for powershell to get powershell working. But I am trying to use the solution from another stackoverflow question that talks about running commands as administrator. I am running a batch script that needs to execute a powershell script (.ps1) as admin, and I don't mind if the user is prompted by UAC or for the password. I am currently using the following command:
powershell.exe -command "&{ Start-Process powershell -ArgumentList '-noprofile -file "C:\long name here.ps1"' -verb RunAs}"
I found this command at https://ss64.com/ps/powershell.html at the bottom where there are details on how to run a powershell command as administrator. The problem with that code is that my powershell script 1. has arguments, and 2. has a long name. I have tried many different iterations of this command with no success, and the ones that DON'T work are listed below:
powershell.exe -command "&{ Start-Process powershell -ArgumentList '-noprofile -file C:\long` name` here.ps1' -verb RunAs}"
powershell.exe -command "&{ Start-Process powershell -ArgumentList '-noprofile -file:"C:\long name here.ps1' -verb RunAs}"
Also, I am completely lost as to how to send arguments to the actual script.
If I'm reading your question correctly - powershell wont find the file as it stops reading the path name when it encounters a blank space?
The example given here specifies that; powershell commands to be run from command prompt as an administrator should have the following syntax:
powershell.exe -noprofile -command "&{ start-process powershell -ArgumentList '-noprofile -file MyScript.ps1' -verb RunAs}"
Couple of ways to achieve what you're looking for. But the easiest method would be to escape the quotes using a ` character. So something similar to;
powershell.exe -noprofile -command "&{ start-process powershell -ArgumentList '-noprofile -file `"C:\long file name.ps1`"' -verb RunAs}"
Also might be worth checking out other answers here
Use a Freeware Third Party Utility
If a freeware third-party executable is permissible, you can use a short tool I wrote called elevate32.exe (32-bit) and elevate64.exe (64-bit) to launch powershell.exe as administrator with the -File parameter and the script arguments you want to use:
elevate64 -- powershell.exe -File "<path>\<long script name>.ps1" -Arg "<long script argument>"
You can get the tool from www.westmesatech.com (copyrighted freeware, free to use anywhere, no installation needed).
Use a WSH Script
If you can't use an external executable, you can also do this (although it does not handle quoting in as robust a manner as the elevate tool's -- parameter) using a Windows Script Host (WSH) script, elevate.js:
var args = WScript.Arguments;
if ( args.Length >= 1 ) {
var exec = args.Item(0);
var cmdLine = "";
for (var i = 1; i < WScript.Arguments.Length; i++ ) {
cmdLine += cmdLine == "" ? '"' + args.Item(i) + '"' : ' "' + args.Item(i) + '"';
}
var shellApp = new ActiveXObject("Shell.Application");
shellApp.ShellExecute(exec, cmdLine, "", "runas");
}
You can call as follows:
wscript.exe "d:\path\elevate.js" powershell.exe -File "C:\long path\script name.ps1" "long script argument"
Self-Elevate your PowerShell Script
Another option is to write a self-elevating PowerShell script. You can check for elevation in the script; if not elevated, it can launch itself elevated and run any command you need. Example:
$isElevated = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if ( -not $isElevated ) {
Start-Process powershell.exe "-File",('"{0}"' -f $MyInvocation.MyCommand.Path) -Verb RunAs
exit
}
& "d:\long path name\script name.ps1" "Long Argument 1" "Long Argument 2"
When you use PowerShell.exe -Command you don't need to use quotes. For example, you can run the following:
PowerShell.exe -Command Get-Service 'wuauserv'
Everything after -Command is interpreted as the command. Note also that double quotes in CMD need escaping with a backslash. Therefore:
powershell.exe -Command Start-Process PowerShell -ArgumentList '-NoProfile -File \"C:\long name here.ps1\"' -Verb RunAs
If your file has arguments:
powershell.exe -Command Start-Process PowerShell -ArgumentList '-NoProfile -File \"C:\long name here.ps1\" \"Arg1\" \"Arg2\"' -Verb RunAs

How to get elevated access to launch the app pool recycle?

I just used this code (on a ps1 file) to recycle my ApplicationPool:
$WebserverName="MySite"
# Load IIS module:
Import-Module WebAdministration
# Get pool name by the site name:
$pool = (Get-Item "IIS:\Sites\$WebserverName"| Select-Object applicationPool).applicationPool
# Recycle the application pool:
Restart-WebAppPool $pool
But it show me this error:
Import-Module : Process should have elevated status to access IIS
So, i searched on internet and i was able to create this .bat file:
#ECHO OFF
#cd ..
#SET DebugLevel=3
#SET PowerShellScriptPath=.\Header.ps1
#SET CurrentScriptName=%~n0.ps1
#PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList ' -NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPath%"" ""%CurrentScriptName%"" ""%DebugLevel%""' -Verb RunAs}"
#pause
I runned it, logged with the administrator user but it shows me a blue screen (from powershell) and suddenly it stops.
I did something wrong?
Thanks!
Try this:
#SET PowerShellScriptPath=.\Header.ps1
#PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList ' -NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPath%"" ' -Verb RunAs}"
You batch has some extra stuff you don't need.
Ensure that the user running this process has admin rights within the box you're attempting to run this against. This wound up solving the issue for me.

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