Home > front end >  Select Object Property in for loop in Powershell
Select Object Property in for loop in Powershell

Time:08-09

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?

CodePudding user response:

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

CodePudding user response:

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.

  • Related