I have written a simple PowerShell code and want to export the results to a file, I get the result correct output onto the console, but only get the last result when I try to export to a file or CSV. Could you help me with where I am going wrong, please?
$files = Get-ChildItem -Path C:\inetpub\SigningWebAPI\Logs\ | Sort-Object lastwritetime
$qapattern = '[NGI][QA]'
$prodpattern = '[NGI][PROD]'
foreach ($file in $files) {
$Totalrequests = (Get-Content -Path $file.FullName | Select-String "started signing process")
$QArequests = (Get-Content -Path $file.FullName | Select-String -SimpleMatch $qapattern)
$Prodrequests = (Get-Content -Path $file.FullName | Select-String -SimpleMatch $prodpattern)
$object = New-Object –TypeName PSObject
$object | Add-Member –MemberType NoteProperty –Name Date –Value ($file.LastWriteTimeUtc.Date).ToShortDateString() -PassThru
$object | Add-Member –MemberType NoteProperty –Name QAKeyrequests –Value $QArequests.count -PassThru
$object | Add-Member –MemberType NoteProperty –Name ProdKeyrequests –Value $Prodrequests.count -PassThru
$object | Add-Member –MemberType NoteProperty –Name TotalRequestsMade –Value $Totalrequests.count -PassThru
}
$object | Export-Csv -Path C:\temp\results.csv
Edit
After applying the comments from Ansgar Wiechers this is the modified version of the code, that works but the output is duplicated 4 times. please see below. wondering where the code is iterating for the result to be displayed times * 4
$files = Get-ChildItem -Path C:\inetpub\SigningWebAPI\Logs\ | Sort-Object lastwritetime
$qapattern = '[NGI][QA]'
$prodpattern = '[NGI][PROD]'
foreach ($file in $files) {
$Totalrequests = (Get-Content -Path $file.FullName | Select-String "started signing process")
$QArequests = (Get-Content -Path $file.FullName | Select-String -SimpleMatch $qapattern)
$Prodrequests = (Get-Content -Path $file.FullName | Select-String -SimpleMatch $prodpattern)
$object = New-Object –TypeName PSObject
$object | Add-Member –MemberType NoteProperty –Name Date –Value ($file.LastWriteTimeUtc.Date).ToShortDateString() -PassThru
$object | Add-Member –MemberType NoteProperty –Name QAKeyrequests –Value $QArequests.count -PassThru
$object | Add-Member –MemberType NoteProperty –Name ProdKeyrequests –Value $Prodrequests.count -PassThru
$object | Add-Member –MemberType NoteProperty –Name TotalRequestsMade –Value $Totalrequests.count -PassThru
}
$object | Export-Csv -Path C:\temp\results.csv
##output:
Date QAKeyrequests ProdKeyrequests TotalRequestsMade
---- ------------- --------------- -----------------
31/10/2017 0 0 0
31/10/2017 0 0 0
31/10/2017 0 0 0
31/10/2017 0 0 0
03/11/2017 0 0 7
03/11/2017 0 0 7
03/11/2017 0 0 7
03/11/2017 0 0 7
04/11/2017 0 0 0
04/11/2017 0 0 0
04/11/2017 0 0 0
04/11/2017 0 0 0
05/11/2017 0 0 0
05/11/2017 0 0 0
05/11/2017 0 0 0
05/11/2017 0 0 0
06/11/2017 0 0 34
06/11/2017 0 0 34
06/11/2017 0 0 34
06/11/2017 0 0 34