tntteam22
tntteam22

Reputation: 1

Powershell store data in variable as text when called by start-job

I have a script that generate a logfile at startup, write things in it, and done. It works well on main script, but the variable gets evaluated again when passed to subscripts using start-job.

Here is how I define this variable :

$logFile = (Get-Location|Select -expand Path)+"\"+(Get-Date -uformat "%Y-%m-%d-%H-%M-%S")+".log"

Here is how I write data to log in the main script :

"here is some log data" | Out-File -FilePath $logFile -Append

Here is how I start a job :

$job=Start-Job -Name "myjob" -FilePath ".\worker.ps1" -ArgumentList
$logFile

The problem is when I write data to the log inside my worker.ps1 subscript, the $logfile value is evaluated again, then I end up having multiple different log files instead of one : because $logFile seems to be evaluated again when called with start-job.

My worker looks like this :

Param (

    [Parameter(Mandatory=$True)]
    [string]$logFile
)

"This is a test" | Out-File -FilePath $logFile -Append

I end up having 2017-02-20-13-55-23.log 2017-02-20-13-56-20.log 2017-02-20-13-57-14.log ...

I believe this is not how it should work, $logFile variable should not get evaluated again, but with jobs I'm getting some funny experiences and I'd like to get some help on this one.

Thanks for ideas

Upvotes: 0

Views: 132

Answers (1)

Ranadip Dutta
Ranadip Dutta

Reputation: 9133

Since you are facing this issue, I will recommend you to put this line inside your worker.ps1. This should help you out:

Param (

    [Parameter(Mandatory=$True)]
    [string]$logFile
)
Remove-Variable logFile -Force -ErrorAction Ignore
"This is a test" | Out-File -FilePath $logFile -Append

This will remove the variable each time before so that a new instance of $logfile will get initiated.

Hope it helps.

Upvotes: 0

Related Questions