4

I'm trying to make a powershell script restart itself in the event of failure. Following on from a couple of references I've found here and here I've added this line...

Invoke-Expression -Command 'cmd /c start powershell.exe -NoExit -file "$PSCommandPath"'

($PSCommandPath is the path and filename of the script) What happens when my script gets to this point is that a window flashes up for a fraction of a second and then closes.

I think (but can't be sure) that the window that appears is a powershell console - it disappears too quickly to read.

The first questions is why isn't the -noexit parameter working - it should make the window of the new process remain open even if there's an error.

The 2nd question is how to get it to work, I've tried various combinations of the command including....

Invoke-Expression -Command 'cmd /c start powershell.exe -NoExit -file c:\my_dir\my_script.ps1 '
Invoke-Expression -Command 'cmd /c start powershell.exe -NoExit -file $PSCommandPath'
Invoke-Expression -Command 'cmd /c start powershell.exe -NoExit -file "$PSCommandPath"'

The only version that does work (almost) is....

Invoke-Expression -Command ($PSCommandPath)

which does restart the script, but it doesn't do it in a new window it re-starts in the existing window (not what I'm looking for). The script has read and execute permissions (all users). This is a particularly frustrating problem in that I'm pretty sure this was working in the past, so it may be system problem rather than a script problem.


Update - I used Invoke-Expressions because that's what the examples I found used (and at the time I'm sure I got it to work!)

This solutions does work....

  Start-Process -FilePath "$PSHOME\powershell.exe" -ArgumentList '-NoExit', '-File', """$PSCommandPath"""

Thanks

2
  • 3
    Why are you using Invoke-Expression and cmd /c? Just use Start-Process -FilePath "$PSHOME\powershell.exe" -ArgumentList '-NoExit', '-File', """$PSCommandPath""" Commented Oct 25, 2018 at 14:18
  • 1
    Also, consider stopping your use of Invoke-Expression. There are VERY few cases where you need it Commented Oct 25, 2018 at 14:19

1 Answer 1

2

No need to search so far...

. $PSCommandPath

Note the space between the dot and $PSCommandPath.

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

1 Comment

Doesnt the first script continue running and not proceed to the next line until the "relaunched" script exits?

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.