How can I increase the value of a variable in an e

2020-07-10 09:01发布

问题:

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

回答1:

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


回答2:

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)"`


回答3:

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 }


标签: powershell