Is it possible to include function reference in scripblock{}?

Hello,

Is it possible to do something like below?

function a {
write-output "AAA"
}

[scriptblock] $b = {
a
}

Yep, that’s fine. The only difference between a function and a script block assigned to a variable like that is the name. :slight_smile:

This does not work though. How do I calla function a in scriptblock?

Works fine for me. Keep in mind that in your example code, you haven’t actually executed the script block that’s assigned to the $b variable. If you add this statement after your code, you execute $b, which calls “a”:

& $b

Can you give a real example of why you would do this?

I need to include function in scriptblock and then use tis scripblock as a parameter to third party cmdlet (namely Invoke-Parallel). So far I did not figure out how to do that except for pasting entire function to into scriptblock before passing it to cmdlet.

Ah. That would depend on what Invoke-Parallel is doing with that object once you pass it in. It’s probably running it in a separate runspace, where your other function doesn’t exist.

Yes, that’s what is being used (https://github.com/RamblingCookieMonster/Invoke-Parallel).
So I assume I have to hardcode everything into [scriptblock] for this to work.

$.02 While Boe is as smart as they come in the PS arena and his scripts are intriguing…I don’t think all this runspace stuff is even necessary. If you do, you need to relax your schedule a bit. The box of pop-tarts says to microwave for three seconds…I don’t have that kinda time :smiley:

Pass your script block to the function as a parameter.

$b = {$env:computername}

function a
{
param($scriptblock)

&$scriptblock

}

a $b

Powershell is not meant to be complicated.

this code works.
Is is not plain function using but not including full function text :slight_smile:

PS C:\> function aaa($msg) { Write-Host ('FUNC says '+$msg+" to You") }
PS C:\> $sb1 = [scriptblock]::Create( "function aaa { $function:aaa }; aaa `$_ " )
PS C:\> 1..10 | invoke-parallel -scriptblock $sb1
FUNC says 1 to You
FUNC says 2 to You
FUNC says 3 to You
FUNC says 4 to You
FUNC says 5 to You
FUNC says 6 to You
FUNC says 7 to You
FUNC says 8 to You
FUNC says 9 to You
FUNC says 10 to You

What

 $function:aaa 
inside scriptblock means?

Greg

you can see it yourself :slight_smile:
just type

PS C:> function aaa($msg) { Write-Host ('FUNC says '+$msg+" to You") }
PS C:> $function:aaa

it’s redefinition of your outside function (aaa) in a scriptblock :slight_smile:
I use $function namespace just like variables $global namespace instead of code typing, bracket matching and so on.

Technically You get “pasting entire function to into scriptblock before passing it to cmdlet” but without pasting :slight_smile:

Спасибо. Век живи, век учись.