Recursive Job

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 5 years, 9 months ago.

  • Author
    Posts
  • #6033

    by vichtak at 2013-02-25 08:58:23

    Hi every body,

    i made a recursive function and it works very well.
    This fonction just browse folders recursively (Depth Frist). The code is below


    Function myfunc
    {
    Param(
    [String]$Path = $PWD,
    [Byte]$CurrentDepth = 0
    )

    $VerbosePreference = 'continue'
    Write-Verbose "($CurrentDepth) Enter ScriptBlock with Path Param = $($Path)"

    $CurrentDepth++

    $lst = Get-ChildItem $Path -Force -Exclude $($global:ExludeExtensions) | Foreach-Object `
    {

    If ($_.PsIsContainer) #Its a Folder
    {
    Write-Verbose "($CurrentDepth) Going to Recurse on Folder : $($_.FullName)"
    Try{
    myfunc -Path $_.FullName -CurrentDepth $CurrentDepth
    }Catch [system.exception]
    {
    Write-Error -Message "Error = $($Error)"
    }

    }
    }
    }

    $Path = "C:\SCRIPTS\A"
    myfunc ($Path)

    Then i tryed to transform this function into a Job to run it simultaneously. And the the recursivity stopped to work.
    Below is the the code of the Job .

    Is &$ScriptBlock the googway to recursivly call a job ?


    $ScriptBlock =
    {
    Param(
    [String]$Path = $PWD,
    [Byte]$CurrentDepth = 0
    )

    $VerbosePreference = 'continue'
    Write-Verbose "($CurrentDepth) Enter ScriptBlock with Path Param = $($Path)"

    $CurrentDepth++

    $lst = Get-ChildItem $Path -Force -Exclude $($global:ExludeExtensions) | Foreach-Object `
    {

    If ($_.PsIsContainer) #Its a Folder
    {
    Write-Verbose "($CurrentDepth) Going to Recurse on Folder : $($_.FullName)"
    Try{
    &$ScriptBlock -Path $_.FullName -CurrentDepth $CurrentDepth
    }Catch [system.exception]
    {
    Write-Error -Message "Error = $($Error)"
    }

    }
    }
    }

    $Path = "C:\SCRIPTS\A"

    #Start-Job
    $myJob = Start-Job $ScriptBlock -ArgumentList ($Path)

    #display verbose and Error info
    $myJob.ChildJobs[0].Verbose | Select-Object Message
    $myJob.ChildJobs[0].Error

    #Wait end of the job
    Wait-Job $myJob | Out-Null

    #Retrieve output of the job
    $Output = Receive-Job $myJob

    #display output of the job
    $Output

    #remove the job
    Remove-Job $myJob

    by poshoholic at 2013-02-26 08:44:16

    I believe the problem is that your job doesn't know what $ScriptBlock is. You pass the script block into the job, but when the job is running, what is $ScriptBlock? If you started that job from a ps1 file I don't think it can "see" the $ScriptBlock variable.

    Instead, put your entire function into the script block that you pass to your job and invoke that recursive function with the initial parameter as part of the job. That should work better for you.

You must be logged in to reply to this topic.