如何增加表达式中变量的值? [英] How can I increase the value of a variable in an expression?

查看:33
本文介绍了如何增加表达式中变量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

$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

我想将 $b 的值增加 1.我尝试过 $b++、$b+=、for 循环、do-while,似乎没有任何效果.我该怎么做?

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?

我也尝试了以下附加代码,但我不知道如何增加 $b 的值.

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

推荐答案

对变量b"使用显式脚本范围.递增(++)后不要忘记输出值.

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

这篇关于如何增加表达式中变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆