PowerShell exiting - powershell

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.

Related

Running a text as powershell scripts

I have to run my powershell scripts ONLY with these way:
Get-Content "ScriptName.ps1" -raw | powershell.exe -ExecutionPolicy byPass -NoExit -Command -
It works ok with some scripts but others cannot be executed with these way, even if they work from PowerShell ISE, or Visual Studio code. Executing ends without any output or warnings.
For me, it looks like when we run raw text as a Command for powershell.exe some symbols or commands don't work the same way as we run .ps1 script from ISE or VS code. I cannot find the rules for Execution scripts like these. Could someone help me with the rules, what i need to do with any script before i wanna run it like these?
I have tried escaping special characters with "/" but it doesnt work
PowerShell's execution policy is a safety feature that controls the conditions under which PowerShell loads configuration files and runs scripts.
Script editors run PS commands as if you typed them into the console, therefore don't trigger the execution policy in most cases.
Rather than trying to bypass the execution policy this way you should either sign your scripts or put in place a domain policy which allows the script to be run normally.

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

Powershell script - suppress security popup

I downloaded PS script from http://poshcode.org/2216. Whenever I try to run this script, security popup appears: "Run only scripts that you trust. While Scripts from the internet can be usefull, this script can potentially harm your computer. If you trust this script, use the Unblock-File cmdlet to allow the script to run without this warning message. (...)".
So I executed Unblock-File .\Send-File.ps1 but nothing changed. I also tried other variations like Get-Content .\SendFile | Unblock-File. Nothing seems to work.
Does anyone know what is the proper way to unblock PowerShell script? Thanks in advance.
You can also wipe the ZoneId from the alternate data stream :
set-Content Send-File.ps1 -Stream zone.identifier -Value ''
To unblock a particular script file, Sam's answer will be ok.
You also can run a script without actually unblocking it by bypassing your PowerShell execution policy explicitly.
To do that execute the following console command:
powershell.exe -ExecutionPolicy Bypass .\Send-File.ps1
... and the script will start
Right-click the downloaded script, select properties and unblock.
By default the downloaded PS script will be treated as unsafe. You need to set Powershell's execution policy to bypass the security check for this particular file.
To do that, execute:
Set-ExecutionPolicy Bypass -File (...)
(Note that it is possible to run the above command with no File specified, which globally sets the execution policy to bypass the security check; we do not recommend you do that!)

Script to change PowerShell ExecutionPolicy

When I setup my system, I use a number of config scripts to have my cosy place to play.
Based on this, I run by double-clicking the following enableps.js:
new ActiveXObject("Shell.Application").ShellExecute(
"powershell", "-noexit -Command \"& Set-ExecutionPolicy RemoteSigned\"", "", "runas");
Because of the -noexit I can issue in the displayed PowerShell window:
Get-ExecutionPolicy
and get as expected:
RemoteSigned
Unfortunately, when opening a new instance of PowerShell, the policy keeps to be Restricted.
If I run in a standard cmd prompt:
cscript "path\to\enableps.js"
it works. But if I embed the command in the enableps.cmd batch and again try to run it by double-clicking, it doesn't work. If I right-click enableps.cmd and use the Runas-Administrator entry, it works again.
So how can I make things working with the standard double-click (plus the related Windows prompt)?
You need to run the command and give it the -Scope argument so that it applies to more than the current session. Add the argument:
-Scope CurrentUser
... and the solution is:
Double click on the file:
// enableps.js
// -----------
new ActiveXObject("Shell.Application").ShellExecute(
"powershell", "-Command \"Set-ExecutionPolicy RemoteSigned\" -Scope CurrentUser",
"", "runas");
Consider replacing RemoteSigned with Unrestricted to allow running downloaded scripts too.
Credit goes to TheMadTechnician, who anyway did not write the full code.
By default making system-wide changes will require you to elevate the process if it hasn't been elevated already. If you want your script to disable the execution policy at the machine level then you will either need to switch off UAC or else you will have to run your cscript using a shellExecute, which will present the user with the required UAC approval dialog.

How to get Hudson CI to execute a Powershell script?

I'm using Hudson version 1.324 for CI and have a couple of issues:
Environment:
Windows Server 2008
Powershell v1.0
Hudson 1.324 running as a service
Hudson Powershell Plugin installed
Psake (aka. "Powershell Make/Rake" available from Github) 0.23
(All current/latest versions as of this initial post)
I have a Powershell (PS) script that works to compile, run NUnit tests, and if successful, create a 7z file of the output. The PS script works from the command line, on both my local development box as well as the CI server where Hudson is installed.
1) Execution Policy with Powershell.
I initially ran a PS console on the server, ran Set-ExecutionPolicy Unrestricted, which allows any script to be run. (Yes, I realize the security concerns here, I'm trying to get something to work and Unrestricted should remove the security issues so I can focus on other problems.)
[This worked, and allowed me to fire off the PS build script from Hudson yesterday. I then encountered another problem, but we'll discuss that more in item #2.]
Once Hudson could fire off a PS script, it complained with the following error:
"C:\Windows\system32\WindowsPowerShell\v1.0\powershell "&
'OzSystems.Tools\psake\psake.ps1' '.\oz-build.ps1'" The term
'OzSystems.Tools\psake\psake.ps1' is not recognized as a cmdlet, funct
ion, operable program, or script file. Verify the term and try again.
At line:1 char:2
+ & <<<< 'OzSystems.Tools\psake\psake.ps1' '.\oz-build.ps1'"
Using the same command line, I am able to successfully execute the PS script from the command line manually. However Hudson is unable to get PS to do the same. After looking at additional PS documentation I also tried this:
"& 'OzSystems.Tools\psake\psake.ps1' '.\oz-build.ps1'"
and got a similar error. There does not appear to be any documentation for the Powershell plugin for Hudson. I've gone through all the Powershell plugin files and don't see anything that's configurable. I can't find a log file for Hudson to get additional information.
Can anyone help me past this?
2) I spent yesterday wrestling with #1. I came in this AM and tried to dig in again, after restarting the Hudson server/service, and now it appears that the ExecutionPolicy has been reset to Restricted. I did what worked yesterday, opened a PS console and Set-ExecutionPolicy to Unrestricted. It shows Unrestricted in the PS console, but Hudson says that it doesn't have rights to execution PS scripts. I reopened a new PS console and confirmed that the ExecutionPolicy is still Unrestriced -- it is. But Hudson evidently is not aware of this change. Restarting Hudson service again does not change Hudson's view of the policy.
Does anyone know what's going on here?
Thanks, Derek
I just ran into the problem of running powershell scripts in hudson. The thing is that you are running a 32-bit process of Java, and you've configured Hudson for 64-bit but not for 32-bit. See the following thread we created at microsoft.
http://social.technet.microsoft.com/Forums/en/winserverpowershell/thread/a9c08f7e-c557-46eb-b8a6-a19ba457e26d
If your lazy.
1. Start powershell (x86) from the start menu as administrator
2. Set the execution policy to remotesigned
Run this once and your homefree.
When Running PowerShell from a scheduled task or Hudson you want to:
Specify the -ExecutionPolicy parameter (in your case: -Ex Unrestricted)
Specify that command using either -Command { ... } or -File NOT BOTH and not without specifying which you mean.
Try this (except that I don't recommend using relative paths):
PowerShell.exe -Ex Unrestricted -Command "C:\Path\To\OzSystems.Tools\psake\psake.ps1" ".\oz-build.ps1"
To be clear, this will work too:
PowerShell.exe -Ex Unrestricted -Command "&{&'OzSystems.Tools\psake\psake.ps1' '.\oz-build.ps1'}"
The first string after -Command is interpreted as THE NAME OF A COMMAND, and every parameter after that is just passed to that command as a parameter. The string is NOT a script, it's the name of a command (in this case, a script file)... you cannot put "&'OzSystems.Tools\psake\psake.ps1'" but you can put "OzSystems.Tools\psake\psake.ps1" even if it has spaces.
To quote from the help (run PowerShell -?) emphasis mine:
-Command
Executes the specified commands (and any parameters) as though they were
typed at the Windows PowerShell command prompt, and then exits, unless
NoExit is specified. The value of Command can be "-", a string. or a
script block.
If the value of Command is "-", the command text is read from standard
input.
If the value of Command is a script block, the script block must be enclosed
in braces ({}). You can specify a script block only when running PowerShell.exe
in Windows PowerShell. The results of the script block are returned
to the parent shell as deserialized XML objects, not live objects.
If the value of Command is a string, Command must be the last parameter
in the command , because any characters typed after the command are
interpreted as the command arguments.
I have been having the same problems as you (as you've seen from my comments). I have given up on the powershell launcher and moved to running things using the batch file launcher. Even though I had set the system to unrestricted that setting didn't seem to matter to hudson's launcher. I don't know if it runs in some other context or something, even adding things to the global profile.ps1 didn't seem to help. What I ended up doing was running
powershell " set-executionpolicy Unrestricted; & 'somefile.ps1'"
which does what I need, although it isn't ideal. I've e-mailed the plugin author about this and will update.
For question #1, try this (assuming you are using PowerShell 2.0):
"C:\Windows\system32\WindowsPowerShell\v1.0\powershell -executionPolicy Unrestricted -file OzSystems.Tools\psake\psake.ps1 C:\{path}\oz-build.ps1"
You are using "." for the path to oz-build.ps1. I suspect you will need to provide the full path to your oz-build.ps1 file to make this work. Unless the infrastructure that executes the command above happens to have the current dir set correctly. And even if it is set correctly for the "process", that only matters to .NET/Win32 API calls and not to PowerShell cmdlets. Current dir in PowerShell is tracked differently than the process's current dir because PowerShell can have multiple runspaces running simultaneously. That sort of global, mutable value doesn't work in this concurrent scenario.
As for question #2, what account does the Hudson service run under? Make sure that account has executed Set-ExecutionPolicy RemoteSigned (or unrestricted).
I just got through this exact problem. What a pain!
If you are running a 32-bit JVM on a 64-bit Windows, make sure that you set the execution policy for the 32-bit Powershell interface. I found my 32 bit executable here:
C:\Windows\syswow64\Windowspowershell\v1.0\powerhsell.exe
The 32- and 64-bit Powershell environments are completely distinct so setting the execution policy in one has no effect on the other.