DEV Community

Pedro Marques
Pedro Marques

Posted on • Originally published at blog.pitermarx.com on

Powershell closures

As a follow up to the previous article, I needed to warn you (and me) about powershell closures. They didn’t work as i expected

$Foo = 1
Write-Host "I expect Foo to be 1: " $Foo
function New-Closure {
param([Scriptblock] $Expression, $Foo = 2)
& $Expression
}
New-Closure -Expression {
Write-Host "I expected Foo to be 1, but was 2: " $Foo
}
New-Closure -Expression {
Write-Host "I expected Foo to be 1, and it is: " $Foo
}.GetNewClosure()

The confusion point for me was that $Foo can be changed by the invoker, unless we add the .GetNewClosure().

As in the previous article the parameter name $ResourceGroupName is very common, it’s best to always use the .GetNewClosure() on the ScriptBlock

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay