How do I Start a job of a function i just defined?

后端 未结 7 815
臣服心动
臣服心动 2020-11-27 23:34

How do I Start a job of a function i just defined?

function FOO { write-host \"HEY\" } Start-Job -ScriptBlock { FOO } |
Receive-Job

Receive-Job: The term \'         


        
7条回答
  •  死守一世寂寞
    2020-11-28 00:04

    @Ben Power's comment under the accepted answer was my concern also, so I googled how to get function definitions, and I found Get-Command - though this gets only the function body. But it can be used also if the function is coming from elsewhere, like a dot-sourced file. So I came up with the following (hold my naming convention :)), the idea is to re-build the function definitions delimited by newlines:

    Filter Greeting {param ([string]$Greeting) return $Greeting}
    Filter FullName {param ([string]$FirstName, [string]$LastName) return $FirstName + " " + $LastName}
    $ScriptText = ""
    $ScriptText += "Filter Greeting {" + (Get-Command Greeting).Definition + "}`n"
    $ScriptText += "Filter FullName {" + (Get-Command FullName).Definition + "}`n"
    $Job = Start-Job `
                -InitializationScript $([ScriptBlock]::Create($ScriptText)) `
                -ScriptBlock {(Greeting -Greeting "Hello") + " " + (FullName -FirstName "PowerShell" -LastName "Programmer")}
    $Result = $Job | Wait-Job | Receive-Job
    $Result
    $Job | Remove-Job
    

提交回复
热议问题