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?
Solution 1 (foreach can found variable):
Solution 2 (with a global variable):
Short version:
Solution 3 (declaration into the loop):