1

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

1
  • You would need to post your script if you want assistance in determining the issue. Or just kill it as suggested. Commented Feb 27, 2015 at 2:04

1 Answer 1

3

Use:Stop-Process $pid or kill $pid at the end of your script. It will kill the power shell instance.

Sign up to request clarification or add additional context in comments.

1 Comment

OMG - wish I had of asked sooner. Thanks so much. I see so many other threads where running with -noexit solves the problem but that's not really a solution when you are running as a scheduled task because the task never ends. This answer is absolutely spot on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.