1

I'm trying to run a function in the background. This function needs to wait a period of time always. I've tried to solve the problem with start-job. But without success (the logs are empty).

My Function

Start-Job { a1 }
function a1()
{
  $timer = [diagnostics.stopwatch]::startnew()
  while ($timer.elapsed.totalseconds -lt 30) 
  {
    writelog "TESTTESTTEST" $timer.elapsed.totalseconds
    start-sleep -seconds 5
  }
  $timer.stop()
}

The log

function writelog([string]$func, [string] $Message, [string] $Value)
{
  $loggingpath = $LogPath+(Get-Date -displayhint date -Format yyyyMMdd)+".txt"
  Add-Content -Path $loggingpath -Value (" ")
  Add-Content -Path $loggingpath -Value ("Date:" + (Get-Date))
  Add-Content -Path $loggingpath -Value ("Function:" + ($func))
}

If I run the code with out start-job everything is working fine!

1 Answer 1

1

Start-Job runs the passed script block in a separate worker process. In this case that process does not have a definition of a1. You need to define both a1 and writelog either in a referenced script (file) or inline in the script block (along with any other dependencies like $LogPath).

Eg. the following does add to the file:

$j = start-job { Add-Content -Path "$env:TEMP\JobDemo.txt" -value "A message at $([datetime]::Now)" }
$j | wait-job
$j | Receive-Job
Get-Content -Path "$env:TEMP\JobDemo.txt"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.