2

I have scheduled a SQLserver agent job that execute a PowerShell script that calls a batch process to start. However, when PowerShell is executed, it did not wait for the batch file to complete before moving to the next job step. What can I do to make it "wait" for the batch file to complete before moving on?

this is the command:

  ([WMICLASS]"\\SERVER\ROOT\CIMV2:win32_process").Create("cmd.exe /c E:\BatchFiles\First_Batch_File.bat") 
BenH
  • 9,766
  • 1
  • 22
  • 35
BIDevLe
  • 37
  • 2
  • 7
  • You've provided us with a single working line from a powershell script, this calls a batch file whose contents we have been excluded from and this runs as a SQL server agent job scheduled by a method also not provided. Let me suggest that a solution could go hand in hand with further pertinent information from yourself. – Compo Mar 29 '17 at 16:46

1 Answers1

2

The Create method will return the ProcessId of the process it creates. You can check if that process has terminated with Get-Process

$process = ([WMICLASS]"\\SERVER\ROOT\CIMV2:win32_process").Create("cmd.exe /c E:\BatchFiles\First_Batch_File.bat")
while ((Get-Process -Id $process.ProcessId -ErrorAction SilentlyContinue) -ne $null) {
    write-host "waiting"
    sleep 2
}
BenH
  • 9,766
  • 1
  • 22
  • 35
  • Paths with spaces will not work this way. Here you need to add escaped double quotes at $batFilePath: $process = ([WMICLASS]"\\$MashineName\ROOT\CIMV2:win32_process").Create("cmd.exe /c `"$batFilePath`"") – Garric Apr 30 '20 at 20:08
  • @Garric The path in the question did not have spaces. – BenH May 01 '20 at 12:38