简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM