greenoldman
greenoldman

Reputation: 21062

Why working script fails when running in the background?

I have such script (here simplified):

while ($true)
{
    Write-Host "Looping..."
    Write-Host "Looping..." 6>> trash.txt
    Start-Sleep -s 1
}

when I run it directly it works, but when I run it in the background:

Start-Job { .\sleeper.ps1 }

for a second it is seen as Running but shortly after as Failed and indeed file "trash.txt" is not created at all, so even one iteration is not executed.

What is wrong here?

Upvotes: 2

Views: 494

Answers (1)

ScriptAutomate
ScriptAutomate

Reputation: 1080

I think the main issue is around the $PWD and -FilePath param, but I will list some info on Write-Host too:

  • Start-Job should be run with the -FilePath parameter. This is because {} is a ScriptBlock object, which is by default taken by the -ScriptBlock parameter, which you do not want. Example solution to that line: Start-Job -FilePath ./script.ps1
  • The $PWD or present working directory is, by default, the home directory / user profile of the current user when executed in a PowerShell job (Linux: $HOME // Windows: $Home/Documents). You can test this by executing a job simply with that variable (it may be $ENV:PWD on Windows?). Either way, it is likely not the same as the directory you are executing this in. trash.txt is being made and appended to, but it is being made in a different directory than your current directory. You will want your script to explicitly include an absolute path to the file being created, or give the script parameters that allow you to input the path at execution. Here is another StackOverflow article where a user had similar struggles, with two good solutions where one uses $args in the script and another uses the -InitializationScript parameter of Start-Job to set the $PWD: PowerShell Start-Job Working Directory
  • Often, Write-Host is low-priority as a selected output vs. using Write-Output / Write-Verbose / Write-Warning / Write-Error. More information about this can be found here: https://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful/ - though, newer versions of PowerShell have added an information stream which I believe may make Write-Host output more accessible. More information on streams can be found with help about_Redirection

Upvotes: 1

Related Questions