3

我正在尝试使用 Get-Content 从文件中读取一个数字并将其添加到一个变量中。

然后我将此数字添加到文件中的字符串中,将数字增加 1,然后再次将其保存到文件中。

我试过类似的东西:

$i = Get-Content C:\number.txt
$i++
Set-Content C:\number.txt

number.txt的内容是:1000

但我得到这个错误:

The '++' operator works only on numbers. The operand is a 'System.String'.
At line:2 char:5
+ $i++ <<<< 
    + CategoryInfo          : InvalidOperation: (1000:String) [], RuntimeException
    + FullyQualifiedErrorId : OperatorRequiresNumber

有没有人知道做这个操作的更好方法?

4

3 回答 3

6

短途:

[decimal]$i = Get-Content C:\number.txt # can be just [int] if content is always integer
$i++
Set-Content C:\number.txt $i
于 2013-01-07T13:54:01.503 回答
6

我猜你需要在递增之前将其转换为整数。

$str = Get-Content C:\number.txt
$i = [System.Decimal]::Parse($str)
$i++
Set-Content C:\number.txt $i
于 2013-01-07T11:46:59.930 回答
0

让我们在一行中完成:

 [decimal] ( $i = Get-Content C:\number.txt ) | % {Set-Content C:\number.txt -value ($_ + 1); return ($_ + 1)}

返回增加的值。$i 具有增量之前的值。

于 2020-08-28T13:41:30.760 回答