PowerShell script to restart a service - powershell

My mission is to press a keyboard sequence, such as Ctrl +Shift +R, to restart a Windows Service.
I have a script which works fine in the PowerShell ISE, when launched with administrative privileges.
When I try with a PowerShell script it fails due to insufficient Administrative Privileges. It’s galling that I can get it to work with an old-fashioned bat file, but not PowerShell.
The root of the problem is that shortcuts to a PowerShell script have their Administrative privileges box greyed out. So far no work-around has overcome this privilege problem.
Any ideas?

One approach is to start another elevated PowerShell session within your script like so:
Start-Process PowerShell.exe -arg '-nologo -noprofile script.ps1' -verb runas
That should prompt to elevate the new PowerShell session. I think you should be able to set the -WindowStyle parameter such that the new window doens't appear (if you need that behavior). Note that you will need to specify the full path to your existing script.

You suggest you don't like solving this problem with a batch file (e.g. net start), I think because batch files are inherently more limited than powershell scripts. What you can do is wrap your Ps script in a batch file, though, for the sake of accomplishing your stated objective -- running a powershell script with a keyboard shortcut without access permissions issues. Try this in a batch file:
powershell set-executionpolicy remotesigned
powershell myscript.ps1

Related

Windows Sandbox PowerShell logon command window not visible

I'm trying to use Windows Sandbox with a PowerShell logon command. This is the LogonCommand section of my WSB file:
<LogonCommand>
<Command>C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -executionpolicy unrestricted -file "C:\\Users\\WDAGUtilityAccount\\Desktop\\boot.ps1" -noexit</Command>
</LogonCommand>
The Windows Sandbox instance loads up okay suggesting no syntactic/validation issues with the WSB file content, but the PowerShell window is not shown. Adding -windowstyle normal has no effect.
I suspect the LogonCommand content is run in a command prompt which is not made visible so running the command to open PowerShell from it somehow "inherits" the terminal window not being visible.
Is it possible to force the PowerShell terminal window to reveal itself in such a case? I want to do this so that I can see the errors that I get because the PowerShell script is not executing as expected and I'm blind to any output/progress indication.
Found an answer (doesn't look like the cleanest option, but works):
<Command>powershell -executionpolicy unrestricted -command "start powershell {-noexit -file C:\Users\WDAGUtilityAccount\Desktop\boot.ps1}"</Command>
powershell switches from CMD to PowerShell
-windowstyle normal won't work to make this PowerShell window visible
-executionpolicy unrestricted allows the nested PowerShell to run from file
start powershell runs another PowerShell with visible window
Running this directly for LogonCommand will not work
-noexit tells the nested PowerShell to remain visible
This is not necessary but it is useful for debugging the script errors
-file C:\Users\WDAGUtilityAccount\Desktop\boot.ps1 runs the given script
Share it with the machine by using a MappedFolder in the WSB configuration

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

PowerShell exiting

I have a script I wrote in PowerShell ISE that works perfectly.
It even works if I copy and paste it into regular PowerShell. However when I run it with regular PowerShell by making it the default program to open it with, then double-clicking, it just opens, displays some red text, and closes.
Is there a way to stop it from closing so I can view the red text or is this a common issue that can be fixed easily?
Try running from cmd prompt using:
powershell -noexit <path to the script>
Additionally, I think the error script may be throwing could be due to execution policy on your machine blocking the script from executing. Otherwise transcript would work. Ensure that the execution policy is set appropriately using Set-ExecutionPolicy cmdlet.
The practice of setting Powershell scripts to run when double clicked is highly discouraged for security reasons. Please ensure you are aware of the risks involved before you proceed.
You cannot simply 'make Powershell as default program' through the Windows Explorer interface. The Run with Powershell context menu option uses the following command:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
The "safest" way (bearing in mind the above caveat) to do what you are trying to achieve is to use Default Programs Editor to set the Run with Powershell context menu option to be the default.

running a bat file and powershell with elevated priviliges

so i have a bat file that goes:
powershell -noexit "My\file\location\myscript.ps1"
the bat file is in the start up. the powershell script changes the bcd. when executed in this manner it says i do not have privileges, access denied, and nothing in the bcd is changed.
sorry for being a newb, but is there a way to pass an elevated privileges value from the bat to the powershell script?
I don't know if this is possible to do from outside Power Shell but it can be done from inside. It's hacky but you could run a power shell script from your bat file that then launches the admin Power Shell session using "PS> Start-Process powershell -Verb runAs".
PowerShell: Running a command as Administrator

Set up PowerShell Script for Automatic Execution

I have a few lines of PowerShell code that I would like to use as an automated script. The way I would like it to be able to work is to be able to call it using one of the following options:
One command line that opens PowerShell, executes script and closes PowerShell (this would be used for a global build-routine)
A file that I can double-click to run the above (I would use this method when manually testing components of my build process)
I have been going through PowerShell documentation online, and although I can find lots of scripts, I have been unable to find instructions on how to do what I need. Thanks for the help.
From http://blogs.msdn.com/b/jaybaz_ms/archive/2007/04/26/powershell-polyglot.aspx
If you're willing to sully your beautiful PowerShell script with a little CMD, you can use a PowerShell-CMD polyglot trick. Save your PowerShell script as a .CMD file, and put this line at the top:
#PowerShell -ExecutionPolicy Bypass -Command Invoke-Expression $('$args=#(^&{$args} %*);'+[String]::Join(';',(Get-Content '%~f0') -notmatch '^^#PowerShell.*EOF$')) & goto :EOF
If you need to support quoted arguments, there's a longer version, which also allows comments. (note the unusual CMD commenting trick of double #).
##:: This prolog allows a PowerShell script to be embedded in a .CMD file.
##:: Any non-PowerShell content must be preceeded by "##"
##setlocal
##set POWERSHELL_BAT_ARGS=%*
##if defined POWERSHELL_BAT_ARGS set POWERSHELL_BAT_ARGS=%POWERSHELL_BAT_ARGS:"=\"%
##PowerShell -ExecutionPolicy Bypass -Command Invoke-Expression $('$args=#(^&{$args} %POWERSHELL_BAT_ARGS%);'+[String]::Join(';',$((Get-Content '%~f0') -notmatch '^^##'))) & goto :EOF
Save your script as a .ps1 file and launch it using powershell.exe, like this:
powershell.exe .\foo.ps1
Make sure you specify the full path to the script, and make sure you have set your execution policy level to at least "RemoteSigned" so that unsigned local scripts can be run.
Run Script Automatically From Another Script (e.g. Batch File)
As Matt Hamilton suggested, simply create your PowerShell .ps1 script and call it using:
PowerShell C:\Path\To\YourPowerShellScript.ps1
or if your batch file's working directory is the same directory that the PowerShell script is in, you can use a relative path:
PowerShell .\YourPowerShellScript.ps1
And before this will work you will need to set the PC's Execution Policy, which I show how to do down below.
Run Script Manually Method 1
You can see my blog post for more information, but essentially create your PowerShell .ps1 script file to do what you want, and then create a .cmd batch file in the same directory and use the following for the file's contents:
#ECHO OFF
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%MyPowerShellScript.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%PowerShellScriptPath%'"
Replacing MyPowerShellScript.ps1 on the 3rd line with the file name of your PowerShell script.
This will allow you to simply double click the batch file to run your PowerShell script, and will avoid you having to change your PowerShell Execution Policy.
My blog post also shows how to run the PowerShell script as an admin if that is something you need to do.
Run Script Manually Method 2
Alternatively, if you don't want to create a batch file for each of your PowerShell scripts, you can change the default PowerShell script behavior from Edit to Run, allowing you to double-click your .ps1 files to run them.
There is an additional registry setting that you will want to modify so that you can run scripts whose file path contains spaces. I show how to do both of these things on this blog post.
With this method however, you will first need to set your execution policy to allow scripts to be ran. You only need to do this once per PC and it can be done by running this line in a PowerShell command prompt.
Start-Process PowerShell -ArgumentList 'Set-ExecutionPolicy RemoteSigned -Force' -Verb RunAs
Set-ExecutionPolicy RemoteSigned -Force is the command that actually changes the execution policy; this sets it to RemoteSigned, so you can change that to something else if you need. Also, this line will automatically run PowerShell as an admin for you, which is required in order to change the execution policy.
Source for Matt's answer.
I can get it to run by double-clicking a file by creating a batch file with the following in it:
C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe LocationOfPS1File
you can use this command :
powershell.exe -argument c:\scriptPath\Script.ps1