How to 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 increase the value of $ b by 1. I tried $ b ++, $ b + =, for the loop, do-while, nothing works. How can i do this?

I also tried the following additional code, but I can not 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 
+6
powershell
source share
3 answers

Use the explicit scope of the script for the variable 'b'. After incrementing (++), do not forget to display the value.

Here is the code that works fine for me (this is a slightly modified version):

 # 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 
+11
source share

This is a small change since I need it in a line. Roman braces do not take threads. You need to use parentheses:

 `"$($script:b++; $script:b)"` 
+1
source share

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

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

All Articles