0

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
1
  • 1
    In the question editor, there is a "curly brace" button. Copy and past your code into the question, then select the code and click the "curly brace" button. Commented Jan 26, 2018 at 12:25

2 Answers 2

2

As veefu already pointed out, you're replacing $object with every iteration, so you end up with just the last object after the loop terminates. Just create and output the objects in the loop and collect the entire loop output in a variable. I would avoid Add-Member, though. You can create objects directly with their properties by passing a hashtable:

$object = foreach ($file in $files) {
    # ...

    New-Object –TypeName PSObject -Property @{
        'Date'              = ($file.LastWriteTimeUtc.Date).ToShortDateString()
        'QAKeyrequests'     = $QArequests.count
        'ProdKeyrequests'   = $Prodrequests.count
        'TotalRequestsMade' = $Totalrequests.count
    }
}

If you have PowerShell v3 or newer you could also use the [PSCustomObject] type accelerator instead of New-Object:

$object = foreach ($file in $files) {
    # ...

    [PSCustomObject]@{
        'Date'              = ($file.LastWriteTimeUtc.Date).ToShortDateString()
        'QAKeyrequests'     = $QArequests.count
        'ProdKeyrequests'   = $Prodrequests.count
        'TotalRequestsMade' = $Totalrequests.count
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I now had simply stored all the results from the for each loop in a variable. as below, the problem is the results are being duplicated 4 times. Where am i going wrong in this approach..?
1

Problem is you're writing to $object over and over again in your loop. You have no code that accumulates the output of the loop. Here's a silly example of how you could accumulate:

$inputThings = @("oneThing","twoThing","threeThing","fourThing")

$outputThings = foreach($thing in $inputThings)  {
    $outputThing = [psobject]::new()
    $outputThing | Add-Member -membertype NoteProperty -name OutputThing -value $thing
    Write-Output $outputThing
}
$outputThings |ConvertTo-Csv

3 Comments

Does that really work? Does Write-Output return the thing it's writing? And does the foreach loop magically accumulate it?
@PalleDue Yes. Write-Output is optional, though. Putting $outputThing instead of Write-Output $outputThing would do the exact same thing: output the value of $outputThing on the success output stream.
@Ansgar Wiechers: Thanks. I knew that just putting outputThing would return the value, but I wasn't aware that Write-Output had the same effect. Always good to learn something new.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.