How to execute a PowerShell script from Notepad++ - powershell

I am using Notepad++ to edit a PowerShell file and want to be able to execute that file from inside Notepad++.
How can I set that up?

It took me a little fiddling, but I finally got this working. (I am using version 1.0 but this should work in other versions as well.)
Notepad++ can be set up to run commands, and assign shortcuts to those commands, as follows:
From the menu, click Run → Run
Add the command
C:\NotepadRun.bat "$(FULL_CURRENT_PATH)"
Save the command, giving it a name and a key shortcut.
Below are the contents of the batch file. I named mine NotepadRun.bat, but you can name it whatever.
#echo off
GOTO %~sx1
:.ps1
cd "%~d1%~p1"
powershell.exe .\%~n1%~sx1
GOTO end
:.rb
ruby "%~f1"
GOTO end
:.php
php "%~f1"
GOTO end
:end
pause
As a note upgrading to Windows7 and Powershell 2 I found some Issues with this and have updated to passing in an ExecutionPolicy to ensure I can run the script I am editing.
:.ps1
cd "%~d1%~p1"
powershell -ExecutionPolicy Unrestricted -File "%~n1%~sx1"
GOTO end

See Using Notepad++ to Compile and Run Java Programs and replace "javac" with "C:Windows\system32\WindowsPowerShell\v1.0\powershell.exe" (or your path to PowerShell). (Caveat: I'm not a Notepad++ user and haven't tried this.)
That said, I'd just use PowerShell ISE (installs with PowerShell) or one of the other dedicated PowerShell IDEs instead.

I would recommend using PowerShell ISE which comes as part of PowerShell and designed specifically for Powershell.

You can run a saved script from "Run" -> "Run" menu in Notepad++ with the following command:
powershell.exe -noexit -command . \"$(FULL_CURRENT_PATH)\"

Based on the answers before:
powershell.exe -ExecutionPolicy Unrestricted -NoLogo -File "$(FULL_CURRENT_PATH)"
You can also add the -NoExit parameter to keep PowerShell from closing automatically:
powershell.exe -ExecutionPolicy Unrestricted -NoExit -NoLogo -File "$(FULL_CURRENT_PATH)"
Note: File has to be saved.

Related

Answer File PowerShell Script To Run On First Boot Of a Fresh Install

I added this FirstLogonCommand to my answer file.
powershell.exe -executionpolicy bypass -NoExit -file D:\DisableGuard.ps1 -Disable
I don't want it to exit to see the output so I added -NoExit
The -Disable switch is the correct switch for the script.
Am I formatting it correctly to run with that switch in an answer file?
It runs correctly if I run it direct from an admin command prompt.
If you run help about_PowerShell.exe in PS it will show you the command, syntax and formatting.
It looks like you have the correct syntax

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 to run a PowerShell script in folder having space in its name?

Running a script in C:\Users\Ooker\Desktop is fine, but yields error in C:\Users\Ooker\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup.
I guess it's because of Start Menu have space in between, but I don't know how to double click the file and make it run. There seems to have no way to bracket the path beforehand.
I can run it in CLI, and it doesn't reference itself.
Few ways to do it.
Registry:
Edit your reg key at
HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\Open\Command
to
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -noLogo -ExecutionPolicy unrestricted -file "%1"
or
Shortcut: Create a shortcut with the target:
powershell.exe -command "& 'C:\Users\Ooker\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\MyScript.ps1'"
keep in mind that the opening in a notepad is a safety measure in the event you accidentally run it when it is not intended.

Run Powershell Silently via NSIS

I have a powershell script that I want to run silently.
I am using NSIS script, it's still promoting the powershell command prompt when .exe file is ran..
Is there a way so it will silently.
!include FileFunc.nsh
!include x64.nsh
OutFile "script.exe"
SilentInstall silent
RequestExecutionLevel admin
Function .onInit
SetSilent silent
FunctionEnd
Section
SetOutPath $EXEDIR
File "script.ps1"
IfSilent 0 +2
ExecWait "powershell -ExecutionPolicy Bypass .\script.ps1 -FFFeatureOff"
SectionEnd
Function .onInstSuccess
Delete "script.ps1"
FunctionEnd
There is an example here that uses silent install, but I couldn't get it working when I tried it. http://nsis.sourceforge.net/Examples/silent.nsi
Try this:
ExecWait "powershell -ExecutionPolicy Bypass -WindowStyle Hidden -File .\script.ps1 -FFFeatureOff"
More info: PowerShell.exe Command-Line Help
You can try ExecShell for this, it allows to hide console via SW_HIDE flag:
ExpandEnvStrings $0 "%COMSPEC%"
ExecShell "" '"$0"' "/C powershell -ExecutionPolicy Bypass .\script.ps1 -FFFeatureOff" SW_HIDE
Also, refer to this question:
Exec vs ExecWait vs ExecShell vs nsExec::Exec vs nsExec::ExecToLog vs nsExec::ExecToStack vs ExecDos vs ExeCmd
Powershell.exe is a console application and console applications get a console window by default and the NSIS silent parameter has no impact on console windows created for child processes. A parameter like -WindowStyle Hidden that can be passed to the child process will always cause a console window to be visible on the screen for a short period of time because Windows will create the console window before the child process starts running.
If you need to hide a console window then you should use a plugin. nsExec is part of the default install or you could use a 3rd-party plugin like ExecDos that offers more advanced features like stdin handling.
If you don't need to wait for the child process then you can try ExecShell as suggested by Serge Z...

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