Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

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
like image 493
Awsaf Avatar asked Jan 31 '11 22:01

Awsaf


1 Answers

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
like image 163
Roman Kuzmin Avatar answered Sep 30 '22 06:09

Roman Kuzmin