我试图从带有Get-Content的文件中读取一个数字并将其添加到变量中.
然后我将此数字添加到文件中的字符串,将数字增加1,然后再将其保存到文件中.
我尝试过类似的东西:
$i = Get-Content C:\number.txt
$i++
Set-Content C:\number.txt
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
有没有人知道更好的方法来做这个操作?
我猜你需要在增加之前将其转换为整数.
$str = Get-Content C:\number.txt
$i = [System.Decimal]::Parse($str)
$i++
Set-Content C:\number.txt $i
Run Code Online (Sandbox Code Playgroud)
简短的方法:
[decimal]$i = Get-Content C:\number.txt # can be just [int] if content is always integer
$i++
Set-Content C:\number.txt $i
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6631 次 |
| 最近记录: |