Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading and increasing a number in a textfile with ++ or equivalent

Tags:

powershell

I am trying to read a number from a file with Get-Content and adding it to a variable.

Then i add this number to a string in a file, increase the number by 1, then save that to the file again.

I have tried something like:

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

The content of number.txt is: 1000

But i get this error:

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

Does anyone have any idea of a better way of doing this operation?

like image 781
Kristoffer Berg Avatar asked Sep 15 '25 07:09

Kristoffer Berg


1 Answers

I guess you need to convert it to an integer before increment it.

$str = Get-Content C:\number.txt
$i = [System.Decimal]::Parse($str)
$i++
Set-Content C:\number.txt $i
like image 199
Davide Berra Avatar answered Sep 18 '25 23:09

Davide Berra