Hello,
Is it possible to do something like below?
function a {
write-output "AAA"
}
[scriptblock] $b = {
a
}
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. ![]()
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 (GitHub - RamblingCookieMonster/Invoke-Parallel: Speed up PowerShell with simplified multithreading).
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 ![]()
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 ![]()
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:aaainside scriptblock means?
Greg
you can see it yourself ![]()
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 ![]()
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 ![]()
Š”ŠæŠ°ŃŠøŠ±Š¾. ŠŠµŠŗ живи, век ŃŃŠøŃŃ.