Home > Software engineering >  PowerShell batch script Timeout ERROR: Input redirection is not supported, exiting the process immed
PowerShell batch script Timeout ERROR: Input redirection is not supported, exiting the process immed

Time:01-09

I need to have a timeout in powershell code where I'm running batch file, in case the batch file runs for a longer time or gets stuck. I also have a timeout in the batch script timeout 300> nul from which I seem to be getting this error and it is just skipping through the timeout and executing next lines. I do not get this error if I remove the timeout from batch script. But I need timeouts at both places, how do I resolve this ? Error- ERROR: Input redirection is not supported, exiting the process immediately.

PS Code-

$bs={
cd D:\files\ 
cmd.exe /c "mybatchfile.bat"
}
$timeoutseconds=800
$j=Start-Job -Scriptblock $bs
if(wait-Job $j -Timeout $timeoutseconds) {Receive-Job $j}
Remove-Job -force $j

batch script is something like this

cmd1
cmd2
timeout 300> nul
cmd3

CodePudding user response:

  • Whenever timeout.exe detects that its stdin input is redirected (not attached to a console), it aborts with the error message you saw.

  • Because of how background jobs launched with Start-Job are implemented, whatever external processes you run from the job's script block invariably see stdin as redirected, so you won't be able to call timeout.exe.[1]

Your best bet is to use thread-based background jobs, where this problem doesn't arise:

  • Start-ThreadJob runs your script block in a separate thread in the same process, and stdin redirection isn't involved; also, because no new PowerShell (child) process must be started, thread jobs are faster to create and require fewer resources.

  • Start-ThreadJob is part of the ThreadJob module, which comes with PowerShell (Core) 7 , and can be installed on demand in Windows PowerShell (e.g., with Install-Module -Scope CurrentUser ThreadJob)

Since Start-ThreadJob also integrates with PowerShell's job-management infrastructure and shares the core parameter syntax with Start-Job, all that should be necessary is to replace Start-Job with Start-ThreadJob in your code.


[1] Unless there is a way to reattach stdin to the console in a timeout.exe call - I'm not aware of such a feature, however (<CON creates an Access denied error).

CodePudding user response:

you might be intersted to add a delay in another way, one alternative is to wait with:

REM # waits a delay before refresh status of service
ping localhost

Indeed i had similar issue on remote powershell issue in a scenario where gitlab agent install script on remote server. by replacing timeout with ping the script do not finish anymore with an error.


My tech youtube channel in my profile

  • Related