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
}
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:
-Append
will append to a preexisting output file on every run. If, instead, the intent is to write the file (anew) in full on every run, omit -Append
.
For technical reasons, [string]
instances and instance of .NET value types can not be modified in-place, and in this case you need to combine -PassThru
with assigning the result back to the input variable (e.g., $var = 101; $var = $var | Add-Member -PassThru Foo Bar
); however decorating instances of these types is best avoided, for the reasons explained in the bottom section of this answer.