Combining Output
A recent question of the PowerShell forum asked how the output of two scripts could be combined. The scripts in question were using Get-ChildItem and Get-Acl to pull back two sets of information related to the file.
PowerShell produces objects. .NET objects with a PowerShell wrapper. The questioner was looking for something like the UNION operator in TSQL. Unfortunately, you can’t combine objects like that. Trying to match up the properties and methods would be a nightmare.
So we need to combine the way we produce the information to create a single object with all of the data we require
| 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015
| $data = @() Get-ChildItem -Path "C:\scripts" -Recurse | foreach { $file = New-Object -TypeName System.Management.Automation.PSObject Add-Member -InputObject $file -MemberType NoteProperty -Name "FullName" -Value $_.Fullname Add-Member -InputObject $file -MemberType NoteProperty -Name "LastAccessTime" -Value $_.LastAccessTime Add-Member -InputObject $file -MemberType NoteProperty -Name "LastWriteTime" -Value $_.LastWriteTime $acl = Get-Acl -Path $_.FullName Add-Member -InputObject $file -MemberType NoteProperty -Name "Owner" -Value $acl.Owner Add-Member -InputObject $file -MemberType NoteProperty -Name "AccessToString" -Value $acl.AccessToString Add-Member -InputObject $file -MemberType NoteProperty -Name "Group" -Value $acl.Group $data += $file } $data | Export-Csv -Path c:\scripts\acl.csv -NoTypeInformation |
Start by using Get-ChildItem to read the directory lists. Then foreach object we create a new object and use Add-Member to create some properties on it. In this case we pick off the full name of the object and the last times it was accessed & written to.
We also need to get some ACL information. We can use Get-Acl within our loop – we only read the file directories once this way. And then we add a few more properties. Add the object to our array and loop back for the next file.
At the end we can dump the information to a csv file for future use.
Read the complete post at http://richardsiddaway.spaces.live.com/Blog/cns!43CFA46A74CF3E96!2365.entry