Is it possible to increment a PowerShell pipe vari

2019-08-26 00:28发布

This question already has an answer here:

I'm trying to count a record as it passes through a pipe. My expression looks like:

$x=28 
gci | Select-Object basename, fullname, @{name='x'; Expression={($x--)}}

I get:

BaseName FullName                x
-------- --------                -
aaoeu    C:\Users\m\x\aaoeu.txt 28
aue      C:\Users\m\x\aue.txt   28
xx       C:\Users\m\x\xx.txt    28

I've tried Add-Member instead of the @ expression as above and that did the same thing - x doesn't alter value per object.

My end-goal is to generate a CSV file so I could use Write-Host to iterate through the Get-ChildItem (gci) output if it's not possible to get my variables to change value as gci emits records.

Am I missing the correct syntax to increment a variable in Select-Object or Add-Member or is it just not possible to do that?

标签: powershell
3条回答
欢心
2楼-- · 2019-08-26 00:59

Solution 1 (foreach can found variable):

$x=28 
gci | %{ $x++; [pscustomobject]@{BaseName=$_.BaseName; FullName=$_.FullName; x=$x}}
查看更多
淡お忘
3楼-- · 2019-08-26 01:06

Solution 2 (with a global variable):

$global:x=28 
Get-ChildItem | select-object basename,fullname,@{name='x'; Expression={($global:x--)}}

Short version:

$global:x=28 
gci | select basename,fullname,@{N='x'; E={($global:x--)}}
查看更多
Melony?
4楼-- · 2019-08-26 01:08

Solution 3 (declaration into the loop):

gci | foreach -Begin {$x=28 } -process { $x++; [pscustomobject]@{BaseName=$_.BaseName; FullName=$_.FullName; x=$x}}
查看更多
登录 后发表回答