'Unable to run batch file from powershell script when it is a scheduled task

I am trying to run a batch file from a powershell script that is a scheduled task. The script sets up a filewatcher and in the action block it calls a batch file using start-process. If I run the action block as a script it works correctly. If I run the whole powershell script from Visual Studio Code, it works correctly. When I schedule the script as a task, the batch file doesn't run. The task is set to run under my account, I am a local administrator and I run it with highest privileges. Get-Executionpolicy returns Remotesigned. The task action block starts powershell with the parameters '-noexit -file "C:\Users\wheckle\Documents\CTA\Projects\Test Automation\windowsTest\watcher\newwatcher.ps1" -ExecutionPolicy Bypass. I use the -Wait option on the start-process cmdlet. It waits from Visual Studio Code; but, it doesn't wait for the command to finish as a task.

$systemBase = "C:\Users\auser\Documents\CTA\Projects\Test Automation\windowsTest\"
$driverFile = $systemBase + "Generate\Driver\chromedriver.exe"
$logfileName = "TestAutomation.log"
$requestFile = "TestRequest.txt"
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path= ($systemBase+"dropfile")
$watcher.EnableRaisingEvents = $true
$watcher.IncludeSubdirectories = $true
$action =
{
   if ($event.SourceEventArgs.ChangeType -eq 'Created') { 
      
        $appFile = ($event.SourceEventArgs.FullPath | split-path -Parent | split-path -Leaf)
    
        $dropBase = $systemBase + "dropfile\" + $appFile +"\"
    
        # check for log file
        if (!(Test-Path -Path ($systemBase + $logfileName) -PathType "Leaf")) {
            new-item -Path ($systemBase + $logfileName) -ItemType "File"
        }
        # Log Starting Project
        "Now Starting the Job for "+$appFile + " at "+ (Get-Date -format "MM-dd-yyyy-HH-mm.fff") | Out-File -FilePath ($systemBase + $logfileName) -Append
        Get-ExecutionPolicy | Out-File -FilePath ($systemBase + $logfileName) -Append
        # Check for group and email files
        if ((Test-Path -Path ($dropBase + $requestFile) -PathType "Leaf")) {
    
            "Executing for "+$appFile + " at "+ (Get-Date -format "MM-dd-yyyy-HH-mm.fff") | Out-File -FilePath ($systemBase + $logfileName) -Append
            # Create execution directory for job
            if (!(Test-Path -Path ($systemBase + "Results\" + $appFile))) {
                $resultsDir = new-item -Path ($systemBase+ "Results\" +$appFile) -ItemType "directory"
            } else {
                $resultsDir = Get-Item -Path ($systemBase+ "Results\" +$appFile)
            }
            "Creating project dir for "+$appFile + " at "+ (Get-Date -format "MM-dd-yyyy-HH-mm.fff") | Out-File -FilePath ($systemBase + $logfileName) -Append
 
            #Create directory for job
            $projectDir = new-item -Path ($resultsDir.FullName+"\"+(Get-Date -format "MM-dd-yyyy-HH-mm.fff")) -ItemType "directory"

            #Copy jar file into executable
            $jarFile = $systemBase + "Generate\" +$appfile+"\JarFile"
            $jarFiles = Get-ChildItem -Path $jarFile

            if (( $null -eq $jarFiles) -or ($jarFiles.count -eq 0)) {
                (Get-Date -format "MM-dd-yyyy HH:mm ")+ "Exiting because of missing jar file for " + $appFile | Out-File -FilePath ($systemBase + $logfileName) -Append
                Return 0
            }
            Copy-Item -Path $jarFiles[0].FullName -Destination $projectDir
            # Create bat file
            $batFile = New-Item -Path $projectDir.FullName -Name "run-automation.bat"  -ItemType "file"
            #create execute line
            $batString = '"%JAVA_HOME%\bin\java"  -jar "'+$projectDir + "\" + $jarFiles[0].Name+'" '
            $batString += Get-Content -Path  ($dropBase + $requestFile) -TotalCount 1
            #add additional lines
            $batDir = $systemBase + "Generate\" + $appFile +"\batfile"
            if (Test-Path -Path ($batDir)) {
                if (Test-Path -Path ($batDir+"preBat.txt")) {
                    Get-Content -Path ($batDir+"preBat.txt") | Set-Content -Path $batFile.FullName
                }
                $batString | Out-File -FilePath $batFile.FullName -Append
                if (Test-Path -Path ($batDir+"preBat.txt")) {
                    Get-Content -Path ($batDir+"postBat.txt") | Add-Content -Path $batFile.FullName 
                }
            } else {
                $batString | Out-File -FilePath $batFile.FullName
            }
            # add config directory
            $configDir = New-Item -Path  $projectDir -Name "config" -ItemType "directory"
            Copy-Item -Path $driverFile -Destination $configDir.FullName
            Copy-Item -Path ($systemBase+"Generate\"+$appFile+"\config\*") -Destination $configDir.FullName
            $emailStr = "toEmail=" 
            Write-Host 
            if (Test-Path -Path  ($configDir.FullName+"\testconfig.properties")) {
                $emailStr += (Get-Content -Path ($dropBase+$requestFile) -TotalCount 2)[-1] 
                $emailStr | Add-Content -Path ($configDir.FullName+"\testconfig.properties")
            } else {
                $emailStr += (Get-Content -Path ($dropBase+$requestFile) -TotalCount 2)[-1] 
                $emailStr | Set-Content -Path ($configDir.FullName+"\testconfig.properties")
            }
            Set-Location $projectDir
            $exeResults = new-item -Path $projectDir.FullName -Name "ExcutionResults.txt" -ItemType "file"
            "Starting Batch Process for "+$appFile + " at "+ (Get-Date -format "MM-dd-yyyy-HH-mm.fff")+ " file "+  $batFile.FullName| Out-File -FilePath ($systemBase + $logfileName) -Append
            Start-Process -FilePath $batFile.FullName -Wait -NoNewWindow | Out-File -FilePath $exeResults.FullName
            "Ended Batch Process for "+$appFile + " at "+ (Get-Date -format "MM-dd-yyyy-HH-mm.fff") | Out-File -FilePath ($systemBase + $logfileName) -Append
           Remove-Item -Path ($dropBase + $requestFile) 
        } else {
            "Invalid file for  "+$appFile + " at "+ (Get-Date -format "MM-dd-yyyy-HH-mm.fff") | Out-File -FilePath ($systemBase + $logfileName) -Append
        }
    }
}
Register-ObjectEvent -InputObject $watcher -EventName Created -Action $action -SourceIdentifier FSCreate1


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source