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?

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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.
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

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.