-1

I want to launch a batch file after a file becomes available (after it is copied by a separate robocopy job).

Below is the command I tried.

Do {Write-Host 'Waiting'; Sleep 10;} While ((Test-Path -Path C:\Temp\file.txt) -eq $False) {Start-Process "cmd.exe" "/c C:\Temp\file.bat" -NoNewWindow -Wait}

However, when the while condition evaluates to False, Powershell merely prints the statement instead of executing it.

lostpacket
  • 1,383
  • 8
  • 26
  • 38
  • If you want it to launch the .bat, you have to tell it so. – Abraham Zinala Feb 24 '22 at 19:24
  • I told it through `Start-Process` but it did not launch. :( – lostpacket Feb 24 '22 at 19:28
  • 3
    You've declared a script block, so the contents of that is printed. Unlike the `do`, there is no actual statement block after the `while` (that's the end of the statement), so just put a new line there (for clarity) and remove the `{ }` from your `Start-Process`. – Jeroen Mostert Feb 24 '22 at 19:30
  • 1
    Ohhhhhhhhhhhhhh, probably helps if i read lol Didn't realize there was more code on the same line. Remove your code from the script block and place it in a new line, or separate it using the semicolon as a means of *statement termination*. Sorry bout the misunderstanding. – Abraham Zinala Feb 24 '22 at 19:32
  • As an aside: To synchronously execute console applications or batch files and capture their output, call them _directly_ (`c:\path\to\some.exe ...` or `& $exePath ...`), do _not_ use `Start-Process` (or the `System.Diagnostics.Process` API it is based on) - see [this answer](https://stackoverflow.com/a/51334633/45375). [GitHub docs issue #6239](https://github.com/MicrosoftDocs/PowerShell-Docs/issues/6239) provides guidance on when use of `Start-Process` is and isn't appropriate. In your case, simply call `C:\Temp\file.bat` – mklement0 Feb 24 '22 at 19:40
  • 1
    Mmm... If you want to launch a Batch-file, why not write the wait code also in Batch? (instead of PS) – Aacini Feb 24 '22 at 19:59
  • @JeroenMostert, I want to run everything on one line, as my client company does not allow to run the Powershell scripts. – lostpacket Feb 24 '22 at 20:47
  • @Aacini yeah good point. – lostpacket Feb 24 '22 at 20:48

1 Answers1

1

Remove the curly brace as @jeroen-mostert has pointed out.

Do {Write-Host 'Waiting'; Sleep 10;} While ((Test-Path -Path C:\Temp\file.txt) -eq $False) Start-Process "cmd.exe" "/c C:\Temp\file.bat" -NoNewWindow -Wait

or can also add a semi-colon for readability

Do {Write-Host 'Waiting'; Sleep 10;} While ((Test-Path -Path C:\Temp\file.txt) -eq $False) ; Start-Process "cmd.exe" "/c C:\Temp\file.bat" -NoNewWindow -Wait
lostpacket
  • 1,383
  • 8
  • 26
  • 38