Page 1 of 1

Script only runs correctly when "Run Project from Console"

Posted: Sun Aug 07, 2016 10:18 pm
by jpbobrek
I'm on the latest version of Sapien PowerShell Studio on a x64 Win10 box, but I'm writing this script to run on all of our business systems (x64 Win 7, 8, and 10).

The script is intended to run in the background to wait for the insertion of a removable storage device and then displays a form with Agree/Disagree buttons. If they agree, then it just goes away. If they disagree, it safely ejects the device. I plan on running this as a scheduled task to start on logon. I had an earlier version of the script that used a shell popup notification which worked great, but I want to replace that bland popup with a nice custom Windows form with our corporate logo (which i removed temporarily in the attached project file).

When I run this project using the "Run Project in Console", it works exactly as I want. Lovely-jovely.
When I try to compile it to .exe, the executable exits instead of just running in the background. Not sure why. I've tried all kinds of options.
When I try to export it to a .ps1, it seems to pop-up the form (the screen flashes where the form should appear), but I don't see it and I tried to run as admin and as regular user with the same outcome.

The attached Project has four files:
USBNotify.psproj <- Main project file
Startup.pss <- I put the bulk of my (sit and wait for device insertion script in here cuz it seemed like the right place)
Global.ps1 <- Left it at default
MainForm.psf <- Simple form

Can someone please take a look see and tell me what I'm doing wrong. Many thanks for your help!

Re: Script only runs correctly when "Run Project from Console"

Posted: Mon Aug 08, 2016 2:58 am
by jvierra
Add this line:

.... >>> while(1){sleep -milli 100} <<< ----
#Write-EventLog -LogName Application -Source "USBNotify" -EntryType Information -EventID 1 -Message "USBNotify Exiting"
$global:ExitCode = 0 #Set the exit code for the Packager

Re: Script only runs correctly when "Run Project from Console"

Posted: Mon Aug 08, 2016 1:35 pm
by jpbobrek
Thanks again Jvierra!! You Rock! That allowed it to compile and keeps it running in the background!

while(1){sleep -milli 100}
So, every .1 seconds, it checks to see if a removable storage device is inserted. Is that right? Honestly, I don't even know why the code gets to that loop in the exe form.

Is there a more cpu-efficient way to achieve the same effect? A colleague suggested (haven't tried yet):
while ($true) {Wait-event -SourceIdentifier "RemovableDiskDetection"}

Re: Script only runs correctly when "Run Project from Console"

Posted: Mon Aug 08, 2016 1:51 pm
by jvierra
No. It just keeps the loop alive be sleeping a lot in 100 millisecond bytes. The reason you were failing is because the program was exiting.