Saturday, September 3, 2011

Compound variable assignment as [array[]] based storage

Below is a function I have written to demonstrate a function which recursively checks ownership and access for files modified within a given time span. What I call to your attention is the ability to use the assignment operator ('+=') to store data recursively as highlighted in salmon.  This is mentioned in 'about_assignment_operators' in the help for Powershell V2:

When the value of the variable is an array, the += operator appends the
 values on the right side of the operator to the array. Unless the array is
 explicitly typed by casting, you can append any type of value to the array..."
In the second part of the script below, I pump the results of a foreach loop into an explicitly typed compound assignment variable ("$RecurseList"):



[Array[]]$RecurseList +=  foreach ($folder in $Recurse) {...
 
This structure almost shows some 'lambda' like functionality, enabling the Powershell programmer to operate on a series of objects, return and store values back to the pipeline which can be collected later in the same function for further operations.



function Check-RecentAccessCombined {
[CmdletBinding()]
    Param(
        [Parameter(ValueFromPipeline=$true)]
           [int]$days=1,
        [string]$ErrorActionPreference="SilentlyContinue"
    )

if ($RecurseList) {Clear-variable RecurseList}
$host.UI.RawUI.BufferSize = new-object System.Management.Automation.Host.Size(500,9999)
$Global:StartTime = (get-date) - (new-timespan -days $days)
$Global:Current=$pwd
$List=gci * | where {!$_.psiscontainer}
$Query= foreach ($i in $List) { gci $i |Select FullName,*Time, @{Label="Access";Expression={get-acl $_.PSChildName| % {$_.AccessToString}}}, @{Label="Owner";Expression={get-acl $_.PSChildName| % {$_.Owner}}}}
[Array[]]$Global:RecurseList += $Query | Select LastAccessTime,CreationTime,FullName,Owner,Access| where {$_.LastAccessTime -gt $StartTime} 

$Global:Recurse=ls -recurse * | where {$_.PSISContainer}
[Array[]]$RecurseList +=  foreach ($folder in $Recurse) {
    sl $folder.FullName;
    # $folder.FullName
    $List=gci * | where {!$_.psiscontainer};
    $Query= $List |Select FullName,*Time,@{Label="Access";Expression={get-acl $_.PSChildName| % {$_.AccessToString}}}, @{Label="Owner";Expression={get-acl $_.PSChildName| % {$_.Owner}}};
    $Query | Select LastAccessTime,CreationTime,FullName,Owner,Access| where {$_.LastAccessTime -gt $StartTime}; 
    } 

sl $Current
$RecurseList  | Sort -descending LastAccessTime
}

No comments: