Awsaf
Awsaf

Reputation: 61

How can I increase the value of a variable in an expression?

I have the following code:

$b = 1
Import-Csv c:\Awsaf\powershell\Beforenew.csv | select name, CustomAttribute1, CustomAttribute2, @{n='Counter';e={$b}} | Export-Csv -NoTypeInformation c:\Awsaf\PowerShell\afternew.csv

I want to increment the value of $b by 1. I have tried $b++, $b+=, for loop, do-while, nothing seems to be working. How can I do it?

I have also tried the following additional code, but I cannot figure out how to increase the value of $b.

$b = 0
Import-CSV c:\Awsaf\powershell\afternew.csv -Delimiter ',' | `
ForEach-Object { $_.Counter = "$b"; return $_ } | `
Export-CSV c:\awsaf\powershell\afterX.csv -Delimiter ',' -NoTypeInformation

Upvotes: 6

Views: 10955

Answers (3)

ShawnFeatherly
ShawnFeatherly

Reputation: 2638

This is a slight variation as I needed this in a string. Roman's curly brackets don't take a string. You need to use parentheses:

`"$($script:b++; $script:b)"`

Upvotes: 1

Roman Kuzmin
Roman Kuzmin

Reputation: 42063

Use explicit script scope for the variable 'b'. After increment (++) do not forget to output the value.

Here is the code that works fine for me (it is a slightly changed version of yours):

# Prepare some data for the test
Get-ChildItem | Select-Object Name | Export-Csv test1.csv -NoTypeInformation

# 1) Use explicit script scope for the variable 'b'
# 2) After increment (++) do not forget to output it
$script:b = 0
Import-Csv test1.csv |
select Name, @{n='Counter'; e={$script:b++; $script:b}} |
Export-Csv -NoTypeInformation test2.csv

Upvotes: 11

stej
stej

Reputation: 29469

Ohter option (although not so beautiful) is to use Add-Member. You tried it in your ForEach-Object:

gci | 
  select Name | 
  % -beg {$counter=0} {$counter++; Add-Member -in $_ -name Test NoteProperty $counter -pass }

Upvotes: 0

Related Questions