Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Script doesn't work when starting it by double-clicking

I got some strange behaviour when executing a powershell script.

  • When I run my script using the ISE it works just fine.
  • When I open Powershell.exe and run my script it works just fine.
  • When I open cmd, and start my script using powershell.exe -noexit ./myscript.ps1, myscript works just fine.

When I double-click myscript however, powershell opens for some milliseconds, I see that it shows some error (red font) and the powershell window closes. I'm unable to track down the error causing this problem since the powershell windows closes to fast. I even tried one single big try-catch block around my hole script, catching any [Exception] and writing it down to a log file. However: the log file is not generated (catch is not called).

How can I track that issue? What could possibly be causing the trouble? Please note that my execution-policy is set to unrestricted.

like image 206
omni Avatar asked Dec 07 '12 11:12

omni


2 Answers

Before trying the suggestion invoke this to see your current settings (if you want restore them later):

cmd /c FType Microsoft.PowerShellScript.1

Then invoke this (note that you will change how your scripts are invoked "from explorer" by this):

cmd /c @"
FType Microsoft.PowerShellScript.1=$PSHOME\powershell.exe -NoExit . "'%1'" %*
"@

Then double-click the script, it should not exit, -NoExit does the trick. See your error messages and solve the problems. But now all your scripts invoked "from explorer" keep their console opened. You may then remove -NoExit from the above command and run it again or restore your original settings.


Some details and one good way to invoke scripts in PS v2 is here. Unfortunately it is broken in PS v3 - submitted issue.

like image 161
Roman Kuzmin Avatar answered Sep 25 '22 23:09

Roman Kuzmin


by default, for security reason when you double clic on a .ps1 file the action is : Edit file, not Run file .
to execute your script : right-click on it and choose run with powershell

like image 33
Loïc MICHEL Avatar answered Sep 24 '22 23:09

Loïc MICHEL