Kevin Price
Kevin Price

Reputation: 429

How to use FileInfo objects when multithreading

Im having trouble using deserialized file info object when running multiple threads

Main gets file info and starts a new thread. The thread will load my module file and "use" the file that I got in main

$file = Get-FileInfo -path "test.zip"

$Scriptblock = {

    Import-Module ".\path\to\foo\module.psm1"
    Foo -File $using:file
    }

Start-Job -ScriptBlock $ScriptBlock 

In my thread, Im not able to call $file.Basename because my object is deseralized when passing it into my thread. The Deseralized.IO.fileinfo class has less functionality than the original FileInfo class

I want to be able to have the same functionality with $file in my thread as I do in main

Is there a way for me to do this? Perhaps by reserializing my object..?

Upvotes: 0

Views: 59

Answers (1)

briantist
briantist

Reputation: 47832

I think you'd be better served by passing the file into the scriptblock as a parameter and then calling Get-FileInfo inside the job:

$MyPath = "test.zip"
$Scriptblock = {

    Import-Module ".\path\to\foo\module.psm1"
    Foo -File $using:file
    $file = Get-FileInfo -path $Using:MyPath
}

Start-Job -ScriptBlock $ScriptBlock 

Alternative:

$MyPath = "test.zip"
$Scriptblock = {
    param([String]$Path)

    Import-Module ".\path\to\foo\module.psm1"
    Foo -File $using:file
    $file = Get-FileInfo -path $Path
}

Start-Job -ScriptBlock $ScriptBlock -ArgumentList $MyPath

Upvotes: 1

Related Questions