X Tutup
Skip to content

Background job operator does not work when invoking a script block variable #9703

@KirkMunro

Description

@KirkMunro

When a variable with a script block is passed to a background job via using, the variable inside the job is a string instead of a script block.

As @bpayette indicated below, this was by design to reduce the risk of accidentally executing code; however, this clearly seems like a design flaw now that we have the & background operator in PowerShell, and while it can be worked around, any code that works around it should be unnecessary. It is worth mentioning that the workaround demonstrated below would continue to work even if this bug was fixed because objects of type scriptblock convert implicitly to string, so the likelihood of this causing an issue for folks if it was fixed should be very low.

Steps to reproduce

Invoke-Pester -ScriptBlock {
    Describe 'Tests for using variables of specific types' -Tags 'CI' {
        It 'Implicit using with background job operator and variable of type ScriptBlock' {
            $sb = {Get-Process -Id $pid}
            $job = & $sb &
            $results = $job | Receive-Job -Wait
            $results | Should -BeOfType PSObject
            $results.PSTypeNames | Should -Contain Deserialized.System.Diagnostics.Process
        }
    }
}

Expected behavior

Tests Passed: 1, Failed: 0, Skipped: 0, Pending: 0, Inconclusive: 0

Actual behavior

Tests Passed: 0, Failed: 1, Skipped: 0, Pending: 0, Inconclusive: 0

Workaround

Invoke-Pester -ScriptBlock {
    Describe 'Tests for using variables of specific types' -Tags 'CI' {
        It 'Implicit using with background job operator and variable of type ScriptBlock' {
            $sb = {Get-Process -Id $pid}
            $job = & ([scriptblock]::Create($sb)) &
            $results = $job | Receive-Job -Wait
            $results | Should -BeOfType PSObject
            $results.PSTypeNames | Should -Contain Deserialized.System.Diagnostics.Process
        }
    }
}

Environment data

Name                           Value
----                           -----
PSVersion                      6.2.0
PSEdition                      Core
GitCommitId                    6.2.0
OS                             Microsoft Windows 10.0.17763
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get aResolution-No ActivityIssue has had no activity for 6 months or moreWG-Enginecore PowerShell engine, interpreter, and runtime

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      X Tutup