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

ConanTheGerbil
  • 677
  • 8
  • 21
  • 3
    Why are you using `Invoke-Expression` and `cmd /c`? Just use `Start-Process -FilePath "$PSHOME\powershell.exe" -ArgumentList '-NoExit', '-File', """$PSCommandPath"""` – Maximilian Burszley Oct 25 '18 at 14:18
  • 1
    Also, [consider stopping your use of `Invoke-Expression`](https://blogs.msdn.microsoft.com/powershell/2011/06/03/invoke-expression-considered-harmful/). There are VERY few cases where you __need__ it – Maximilian Burszley Oct 25 '18 at 14:19

1 Answers1

2

No need to search so far...

. $PSCommandPath

Note the space between the dot and $PSCommandPath.

buddemat
  • 4,552
  • 14
  • 29
  • 49