简体   繁体   中英

How to enumerate a Format-Table entry in PowerShell?

I have an array of hashes, and I want that array to be formatted as a table with each entry enumerated without actually adding a hash item to contain this information. Eg

$id = 0
$items = @( @{ item='a' }, @{ item='b' }, @{ item='c' })
$items |
 %{ new-object PSObject -Property $_ } |
  Format-Table @{ n=""; e={ "{0}" -f ++$id }; a="left" },item

I'm expecting:

  item
- ----
1 a   
2 b   
3 c   

but getting:

  item
- ----
1 a   
1 b   
1 c   

Seems that the $id is passed by value. Need to force it as a reference using [ref] and it'll work. Eg:

[ref]$id = 0
$items = @( @{ item='a' }, @{ item='b' }, @{ item='c' })
$items | %{ new-object PSObject -Property $_ } |
 Format-Table @{ n=""; e={ "{0}" -f ++$id.value }; a="left" },item

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM