-
-
Save Jaykul/f7b2dfc7ec06da7f02ddb7a41c983018 to your computer and use it in GitHub Desktop.
How to capture a variable value in a closure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function global:Get-CompFolder{ | |
param($iFolderLoc) | |
$objCompFolder = [Ordered]@{ | |
'Location' = $iFolderLoc | |
'Folder' = Get-Item $iFolderLoc | |
'SortedTree' = @() | |
} | |
New-Object -TypeName PSObject -Property $objCompFolder | | |
Add-Member -Passthru -Type ScriptProperty -Name Tree -Value { | |
$root = $this.Folder.PSPath | |
Get-ChildItem $root -Recurse | % { | |
$_ | Add-Member -PassThru -Type NoteProperty -Name RelativeName -Value ( | |
"." + $_.PSPath.SubString($root.Length) | |
) | |
} # No closure, because NoteProperty is calculated at assignment | |
} # Closure Not needed, because we get iFolderLoc from $this.Folder | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function global:Get-CompFolder{ | |
param($iFolderLoc) | |
$objCompFolder = [Ordered]@{ | |
'Location' = $iFolderLoc | |
'Folder' = Get-Item $iFolderLoc | |
'Tree' = Get-ChildItem $iFolderLoc -Recurse | | |
Add-Member -MemberType ScriptProperty -Name 'RelativeName' -Force -PassThru -Value { | |
"." + $this.FullName -replace ('.*' + [regex]::escape($iFolderLoc)) | |
}.GetNewClosure() # Without this, $iFolderLoc won't have a value when this is evaluated later... | |
'SortedTree' = @() | |
} | |
return New-Object -TypeName PSObject -Property $objCompFolder | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment