Reputation: 3998
I'm trying to write a small Powershell function that will return some summary data from some XML log files. I wrote a short summarizing function:
function Summarize-Log( $log )
{
$obj = New-Object Object
$obj | Add-Member NoteProperty Date $log.lastwritetime
$obj | Add-Member NoteProperty Passed ([xml](get-content $log)).suite.passed
$obj | Add-Member NoteProperty NotImplemented ([xml](get-content $log)).suite.notImplemented
return $obj
}
I think I should be able to call this function like this:
dir -recurse $logDirs | where { $_.name -eq "MyLog.xml" } | foreach{ Summarize-Log $_ }
When I call it like this, it seems to read the SAME numbers out of each pass through the loop. The Date property is correct, but the two properties being read from the XML are incorrect, as if the get-content call is returning the same data regardless of the input parameter.
How do I fix this?
Right now it appears from the code as if the whole file will be read in twice. Is there a more efficient way to get this information?
Upvotes: 1
Views: 473
Reputation: 52410
Your script looks fine. Are you sure that the dir|where command is actually returning different mylog.xml files?
To not re-read the xml, cache the xml in a variable in your function:
function Summarize-Log( $log )
{
$xml = [xml](get-content $log)
$obj = New-Object pscustomobject
$obj | Add-Member NoteProperty Date $log.lastwritetime
$obj | Add-Member NoteProperty Passed $xml.suite.passed
$obj | Add-Member NoteProperty NotImplemented $xml.suite.notImplemented
$obj
}
Also, try to get out of the habit of using the return keyword (i've removed it from my rewrite) as any value that is not explicitly captured by assignment to a variable will be returned from the function.
edit: use $_.fullname
instead of $_
as $_.tostring()
(which is implied) will resolve to filename only, not path+name.
dir -rec | foreach { summarize-log $_.fullname }
Upvotes: 2