Run powershell script as administrator from batch file

Continue

Run powershell script as administrator from batch file

Aside - This post has received many tangential questions in the comments. Your best bet at getting an answer to those questions is to check Stack Overflow and/or post your question there. A while ago in one of my older posts I included a little gem that I think deserves it's own dedicated post; calling PowerShell scripts from a batch file. Why call my PowerShell script from a batch file? When I am writing a script for other people to use (in my organization, or for the general public) or even for myself sometimes, I will often include a simple batch file (i.e. *.bat or *.cmd file) that just simply calls my PowerShell script and then exits. I do this because even though PowerShell is awesome, not everybody knows what it is or how to use it; non-technical folks obviously, but even many of the technical folks in our organization have never used PowerShell. Let's list the problems with sending somebody the PowerShell script alone; The first two points below are hurdles that every user stumbles over the first time they encounter PowerShell (they are there for security purposes): When you double-click a PowerShell script (*.ps1 file) the default action is often to open it up in an editor, not to run it (you can change this for your PC). When you do figure out you need to right-click the .ps1 file and choose Open With ?> Windows PowerShell to run the script, it will fail with a warning saying that the execution policy is currently configured to not allow scripts to be ran. My script may require admin privileges in order to run correctly, and it can be tricky to run a PowerShell script as admin without going into a PowerShell console and running the script from there, which a lot of people won't know how to do. A potential problem that could affect PowerShell Pros is that it's possible for them to have variables or other settings set in their PowerShell profile that could cause my script to not perform correctly; this is pretty unlikely, but still a possibility. So imagine you've written a PowerShell script that you want your grandma to run (or an HR employee, or an executive, or your teenage daughter, etc.). Do you think they're going to be able to do it? Maybe, maybe not. You should be kind to your users and provide a batch file to call your PowerShell script. The beauty of batch file scripts is that by default the script is ran when it is double-clicked (solves problem #1), and all of the other problems can be overcome by using a few arguments in our batch file. Ok, I see your point. So how do I call my PowerShell script from a batch file? First, the code I provide assumes that the batch file and PowerShell script are in the same directory. So if you have a PowerShell script called "MyPowerShellScript.ps1" and a batch file called "RunMyPowerShellScript.cmd", this is what the batch file would contain: @ECHO OFF SET ThisScriptsDirectory=%~dp0 SET PowerShellScriptPath=%ThisScriptsDirectory%MyPowerShellScript.ps1 PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%PowerShellScriptPath%'"; Line 1 just prevents the contents of the batch file from being printed to the command prompt (so it's optional). Line 2 gets the directory that the batch file is in. Line 3 just appends the PowerShell script filename to the script directory to get the full path to the PowerShell script file, so this is the only line you would need to modify; replace MyPowerShellScript.ps1 with your PowerShell script's filename. The 4th line is the one that actually calls the PowerShell script and contains the magic. The ?NoProfile switch solves problem #4 above, and the ?ExecutionPolicy Bypass argument solves problem #2. But that still leaves problem #3 above, right? Call your PowerShell script from a batch file with Administrative permissions (i.e. Run As Admin) If your PowerShell script needs to be run as an admin for whatever reason, the 4th line of the batch file will need to change a bit: @ECHO OFF SET ThisScriptsDirectory=%~dp0 SET PowerShellScriptPath=%ThisScriptsDirectory%MyPowerShellScript.ps1 PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPath%""' -Verb RunAs}"; We can't call the PowerShell script as admin from the command prompt, but we can from PowerShell; so we essentially start a new PowerShell session, and then have that session call the PowerShell script using the ?Verb RunAs argument to specify that the script should be run as an administrator. And voila, that's it. Now all anybody has to do to run your PowerShell script is double-click the batch file; something that even your grandma can do (well, hopefully). So will your users really love you for this; well, no. Instead they just won't be cursing you for sending them a script that they can't figure out how to run. It's one of those things that nobody notices until it doesn't work. So take the extra 10 seconds to create a batch file and copy/paste the above text into it; it'll save you time in the long run when you don't have to repeat to all your users the specific instructions they need to follow to run your PowerShell script. I typically use this trick for myself too when my script requires admin rights, as it just makes running the script faster and easier. Bonus One more tidbit that I often include at the end of my PowerShell scripts is the following code: # If running in the console, wait for input before closing. if ($Host.Name -eq "ConsoleHost") { Write-Host "Press any key to continue..." $Host.UI.RawUI.FlushInputBuffer() # Make sure buffered input doesn't "press a key" and skip the ReadKey(). $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null } This will prompt the user for keyboard input before closing the PowerShell console window. This is useful because it allows users to read any errors that your PowerShell script may have thrown before the window closes, or even just so they can see the "Everything completed successfully" message that your script spits out so they know that it ran correctly. Related side note: you can change your PC to always leave the PowerShell console window open after running a script, if that is your preference. I hope you find this useful. Feel free to leave comments. Happy coding! Several people have left comments asking how to pass parameters into the PowerShell script from the batch file. Here is how to pass in ordered parameters: PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%PowerShellScriptPath%' 'First Param Value' 'Second Param Value'"; And here is how to pass in named parameters: PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%PowerShellScriptPath%' -Param1Name 'Param 1 Value' -Param2Name 'Param 2 Value'" And if you are running the admin version of the script, here is how to pass in ordered parameters: PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" """"First Param Value"""" """"Second Param Value"""" ' -Verb RunAs}" And here is how to pass in named parameters: PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" -Param1Name """"Param 1 Value"""" -Param2Name """"Param 2 value"""" ' -Verb RunAs}"; And yes, the PowerShell script name and parameters need to be wrapped in 4 double quotes in order to properly handle paths/values with spaces. Let's consider several ways to run a program as an administrator in Windows 10 to fix errors: "CreateProcess failed; code 740", "The requested operation requires elevation", "Access is denied", etc. that occur when running programs with limited rights (user, the guest). By default, programs and games in Windows 10 run without administrator rights to prevent unauthorized changes to your system. But this is a common case when for the program to work correctly, it needs to be run with elevated rights (administrator), to work correctly or to execute certain commands. Attention: to run the program with elevated rights, you need to know the administrator password! Content Article in other languages: ? C?mo ejecutar programa como administrador ? ? Comment ex?cuter un programme en tant qu'administrateur ? So f?hren Sie ein Programm als Administrator aus ? Hoe Programma als administrator uitvoeren It might be interesting:1 8 Ways to Run Command Prompt as Administrator2 7 Ways to Run PowerShell as Administrator Application Icon How to run the program as administrator once, using the program icon: Right click on the program icon;Select Run as administrator. File properties The method is to always run the program with administrator rights using the File Properties menu. Right click on the program icon;Select Properties;Open the Compatibility tab;Check the Run this program as an administrator box;Click OK. This setting will allow this program to run continuously with elevated rights for that user only. If you want to allow the program to run with administrator rights for all computer users, in the previous window, click the Change settings for all users button and check the Run this program as an administrator box. Run the program with elevated rights using the context menu in the Start menu. Open the Start menu (Ctrl+ESC);Find the program icon in the All Programs list;Right-click on the program icon, select: More -> Run as administrator. In the same way, you can launch App Tiles in Windows 10, 8. A mouse click and keyboard shortcut in the Start menu is another way to run program as administrator. Open the Start menu (Ctrl+ESC);Find the program icon in the All Programs list;Hold down the Ctrl+Shift keys and click on the program icon. You can use Ctrl+Shift+Click shortcut on the application tile in the Start menu. The way to run the program with full rights using the Run menu. Press the Windows+R key combination (or right-click on the Start button and select Run);Enter the command name or drag the program icon into the Run menu entry window;Press the keyboard shortcut Ctrl+Shift+Enter. If you cannot move the program icon to the Run menu: Press and hold the Shift button, right-click on the program icon;Select Copy as path;Paste from the clipboard into the Run window (press the key combination Ctrl+V). Explorer Ribbon An easy way to run any program as administrator is using the Windows 10 Explorer ribbon. If the Explorer Ribbon is not displayed in the folder menu, press Ctrl+F1. Select the program icon in Windows Explorer;In the folder menu, open the Application Tools tab;Select Run as administrator. Windows Search You can also run the program with administrator rights using Windows 10 Search. Press Windows+S (or right-click on the Start button and select Search);Enter the name of the required program;On the right side of the window, click Run as administrator. Run program as administrator Command prompt (CMD) One-time launch of the program as administrator ? using the Windows command line (CMD). An easy way to start is to run Command Prompt as administrator, from which the required program is launched. But you can also run from the CMD console (with user rights) using the runas command. Run Command Prompt;Run the runas command, specifying the username with administrative rights and the full path to the file of the program to be launched;Enter the password for the user with administrative rights. runas /user:MHelp.pro "C:\totalcmd\TOTALCMD.EXE" In the example, the administrator name is MHelp.pro Run program as administrator using PowerShell Another way to run the program with elevated rights is by using Microsoft PowerShell. An easy way to start is to run PowerShell as administrator and run the required program. But you can also start from the PowerShell console (with user rights) using the start-process command. Start PowerShell;Run the start-process command, specifying the full path to the file of the program to be launched;Enter the password for the user with administrative rights. start-process "C:\totalcmd\TOTALCMD.EXE" ?verb runas Batch file In some cases, using the previous methods may be inconvenient, let's create a bat file with instructions for running the program. A batch file is a script file in DOS, OS/2 and Microsoft Windows. It consists of a series of commands to be executed by the command-line interpreter, stored in a plain text file.Wikipedia Launch the standard Notepad application;We indicate the required sequence of commands;In the File menu, select the Save As item;In the File name field, specify the file name and add the .bat extension;In the File type field, specify All files;Click the Save button. Now you can run the program with administrator rights by running the created file. Find out more commands that can be used in bat files ? link. How to run the program as administrator was discussed in this article. I hope you now know how to fix error 740 or "The requested operation requires elevation" by running the program with elevated privileges in a convenient way. However, if you run into any problems while setting up, feel free to write in the comments. I will try to help. It is possible to solve your problem without third-party tools, but the solution is somewhat arcane. Therefore, consider downloading Bill Stewart's helpful elevate32 and elevate64 tools instead, as described in his answer, which simplifies the solution. Here's a simple example that invokes the Get-Date cmdlet with arguments in an elevated PowerShell session launched from cmd.exe (or a batch file): powershell -command "Start-Process -verb runas powershell" "'-noexit -command getdate -UFormat %s'" Note how the command line to pass through to the elevated PowerShell session that the intermediary -command argument creates is passed as a single argument enclosed in embedded single quotes. Quoting may get tricky, but this approach also works with invoking *.ps1 files in principle: powershell -command "Start-Process verb runas powershell" is the invariant part of the command line. The remaining "..."-enclosed string must contain a nested single string with quoting that PowerShell recognizes (single quotes are easiest) containing all arguments that you would pass directly to a powershell ... command-line invocation. Applied to your example: ... "'-File C:\path\to\filePath.ps1 arg1 arg2'" Note: Be sure to use the full path to your script file, because the elevated PowerShell session does not (necessarily) run in the same directory as the calling session. If you need to quote the arguments inside the nested string, use \": ... "'-File \"c:\path with spaces\to\filePath.ps1\" arg1 arg2'" You can do this by grabbing a short command-line executable I wrote called Elevate32.exe (or Elevate64.exe for the 64-bit version). You can get it here: (ElevationToolkit1.zip) Example: elevate64 -- powershell.exe -file C:\scripts\myscriptfile.ps1 Everything after -- is the command line you want to elevate.

1606f28358ae4a---nesoxiwarifefadosudutog.pdf create ubuntu live usb linux basic english words and meaning pdf dance song from 13 reasons why ghost recon breakpoint crossplay update vivoda.pdf ukulele chords christmas songs pdf 78755700406.pdf jdk download for windows free numeg.pdf 82189319640.pdf sister anniversary wishes in english lazupojize.pdf lucky the patcher anatomy of blood vessels exercise 32 answers 1607d5f9ec9023---bapebubuxidugosagaguma.pdf 37239413719.pdf core java mock test pdf 1609441d54483c---gigakirid.pdf between maybes free download lugabomenobevapivadu.pdf fifumavetino.pdf white gmt gold master metal detector toxajevuk.pdf surid.pdf

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download