Reputation: 13
I am trying to get a rather long Powershell script to run as a scheduled task. The script runs perfectly when I run it from the Powershell ISE but it doesn't work properly if I simply invoke it from a scheduled task unless I specify -noexit. So I have a batch wrapper script which I call using my scheduled task with -noexit specified and that works fine. However, I call this every 20 minutes and so I end up with a very large build up of Powershell session processes. The scheduled task also never ends because of this. Essentially the script checks for the presence of a USB disk with a specific label and if it is present I copy some files to it.
My problem is that because I am using -noexit, the Powershell session keeps running and as I call the script every 20 minutes, they build up. I need a way to kill the Powershell session once my Powershell script has done its thing. I have tried using exit in the last line of my batch file but it doesn't kill the Powershell session.
How can I kill the Powershell session that has been called using -noexit once my Powershell script has completed running?
Another way to possibly solve this is to determine why the Powershell script doesn't run properly without -noexit when called but runs fine when called from Powershell ISE (which is just running the script directly in a powershell session) - which also works fine.
I have looked at using -command instead of -file, I have looked at different wrapper methods. I have tried using new-pssession and remove-pssession.
The script has a number of if else statements in it and what I find is if I run it from a command prompt without the -noexit is the if part runs but the else part is never run - even when the conditions are correct for it to run the else part. Works fine from a powershell session like I said. Very annoying...
This is driving me insane so any suggestions will be very much appreciated.
Thanks
Upvotes: 1
Views: 2311
Reputation: 1053
Use:Stop-Process $pid
or kill $pid
at the end of your script. It will kill the power shell instance.
Upvotes: 3