powershellrestcsvpsobject

Adding a member on PSobject after receiving it from Invoke Rest-Method results in the Object being $null


I'm using the Invoke-RestMethod to gather information on IP-Addresses from a list automatically. While that itself works like a breeze, I am required to add a timestamp for each time the computer makes a query to the API endpoint, which is where it is resulting in problems when exporting the whole thing into a CSV file:

I am very new to PowerShell since today (except for simply running some pre-written scripts when working in IT Help Desk) but the following problem is current:

When appending the data to the CSV file in the output path, no problems occur - but of course the requirement of the timestamp as a column is missing.

However, when I try to use the Add-Member method to add the new hashvalue to the PSobject resulting from the query (or when I simply import the csv, add the column with the timestamp and export it back to the output file) the whole thing results in $null.

Why does this happen? Is there any way I can possibly add those timestamps into the CSV after each iteration properly?

Code snippet:

try { 
        $timestamp = Get-Date -Format "dd.MM.yyyy HH:mm"
        Invoke-RestMethod @Params 
        | Select-Object ip, country_code, as, is_proxy
        | Add-Member -MemberType NoteProperty -Name "query_date_and_time" -Value $timestamp
        | Export-Csv $OutputPath -Append
        
        # $arr += $Result

        Write-Host "$Result"
        
    } catch { 
        Throw $_.Exception
    }

Solution

  • The Add-Member cmdlet is somewhat unusual in that it modifies its input object in place, instead of outputting a modified object, and by default produces no output - that's why Export-Csv received no input.

    However, you can use the -PassThru switch to request that the modified object be output as well.

    Therefore (pipeline reformatted to be Windows PowerShell-compatible):

    Invoke-RestMethod @Params | 
      Select-Object ip, country_code, as, is_proxy |
      Add-Member -PassThru -MemberType NoteProperty -Name 'query_date_and_time' -Value $timestamp |
      Export-Csv $OutputPath -Append
    

    As an aside: