Skip to content

Instantly share code, notes, and snippets.

@Jaykul
Forked from pinecones-sx/fcobject.ps1
Last active April 8, 2018 01:35
Show Gist options
  • Save Jaykul/f7b2dfc7ec06da7f02ddb7a41c983018 to your computer and use it in GitHub Desktop.
Save Jaykul/f7b2dfc7ec06da7f02ddb7a41c983018 to your computer and use it in GitHub Desktop.
How to capture a variable value in a closure
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
}
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