Search code examples
windowspowershellbatch-filesql-agent-jobget-wmiobject

PowerShell [wmiclass] Win32_Process.Create() then wait for batch file to complete


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") 

Solution

  • 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
    }