PowerShell : How to run a script by double clicking on it ? (without 'Run with Powershell')

104 views Asked by At

[EDIT BELOW : The problem was not the MsgBox]

I got a problem : my MsgBox works fine when I run the code from ISE but does not show up when I execute it by double clicking on .ps1 file.

I tried all what internet could give me (on others forums and on StackOverflow too), that's why you'll see many useless lines (especially many AssemblyName) but I keep them in order to show you what I already tried.

Here is my code :

Set-ExecutionPolicy Unrestricted

Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName 'Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

$msgBody = @'
Hello.

Press OK to export.
'@
$msgTitle = 'Export to Google Drive' 
$msgButton = 'OKCancel'
$msgImage = 'Warning'

$result = [System.Windows.Forms.MessageBox]::Show($msgBody,$msgTitle,$msgButton,$msgImage)

Write-Host "The user chose: $Result ["($result).value__"]"

Thanks for your time and help.

[EDIT]

I have some news : The problem was not the MsgBox, the .ps1 is just NOT running AT ALL when double clicking on it (or calling it with Windows Task Scheduler). I tested it with a simple Write-Host and it doesn't show up either.

What happens is that the Powershell execution window is just opening and closing real quick.

I have an answer for this problem (a bypass more precisely) that I posted as answer to my own post below.

As it's not a general solution to make a script run by double clicking on it, I keep this post opened if anyone has a real answer.

I know it's possible because I have many scripts that runs directly by double clicking on it (without shortcut either).

1

There are 1 answers

1
Rom On

Thanks to @lucas-crespo-ferreira I got a solution, I bypass the problem by calling my script with .BAT and thanks to this, the script runs perfectly and the MsgBox shows up.

Here is the code to write in .BAT :


powershell -noexit "& ""C:\my_path\FolderName\YourPowerShellScriptName.ps1"""

Be sure to modify the path with your own.

I know it's not a general solution to make a script run by double clicking on it so I let this post opened.