1

I am pretty sure there is a simple answer, but I cannot figure out how to ask it accurately enough as I am new to PowerShell.

Simple put, I am doing some API calls and then running through the results. The results include various properties that I converted from JSON into a Powershell Object.

A record looks simply like this:

id               : 10123
path             : /a/path/here/file.pptx
creationDate     : 2019-06-28T09:37:32.000-04:00
modifiedDate     : 2020-03-09T13:56:13.000-04:00
description      : Record Description
creator          : asmith
lastModifiedBy   : jsmith

I then want to interact with the records, so I use a FOR loop on the IDs:

 Foreach($SimpleID in $Records.id){
       Write-Host $SimpleID  + "`t|`t"+ $Records.path >> file.log
}

My question is, I want that output in the file to be:

10123   |   /a/path/here/file.pptx
10124   |   /next/path/file.txt
...etc

I know that the $Records.path is not correct there, but how do I filter it to only print the single path for the ID? I am sure there is a simple way, but I cannot figure out what to look up to start.

Any ideas on where to start?

TheGoblinPopper
  • 149
  • 1
  • 3
  • 12

2 Answers2

2

You cannot use Write-Host to produce data output - see this post.

It sounds like you're looking for the following:

$Records | ForEach-Object { $_.id  + "`t|`t"+ $_.path } > file.log
mklement0
  • 382,024
  • 64
  • 607
  • 775
0

I would like to provide this alternative to mklement0's solution using Set-Content and Add-Content:

Set-Content -Path '.\log' -Value ''
$Records | ForEach-Object { Add-Content -Path '.\log' -Value "$_.id | $_.path" }

Loop over the Records objects and grab only what you need.

  • 1
    Calling `Add-Content` _once for each input object_ is needlessly inefficient, because it opens and closes the file every time (leaving the additional need to initialize the output file aside). By contrast, `> file.log` in my answer applies to the _entire pipeline_,, and therefore opens the file only _once_, and similarly closes it only once, after all input objects have been written. It is, in effect, the equivalent of `| Out-File file.log`, which implies that you can (preferably, for text input) use `| Set-Content file.log` too. – mklement0 Aug 09 '22 at 01:34
  • 1
    My current code is usually the > file.log style already. I used a Write-Host when I was testing something and grabbed the older line – TheGoblinPopper Aug 09 '22 at 01:57