powershell - 使用 C++ 或同等语言读取和增加文本文件中的数字

标签 powershell

我正在尝试使用 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

有人知道执行此操作的更好方法吗?

最佳答案

我想您需要在增加它之前将其转换为整数。

$str = Get-Content C:\number.txt
$i = [System.Decimal]::Parse($str)
$i++
Set-Content C:\number.txt $i

关于powershell - 使用 C++ 或同等语言读取和增加文本文件中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14194915/

相关文章:

powershell - PowerShell:读取文本,正则表达式排序,将输出写入文件和格式化

azure - 使用 Azure CLI 从变量创建 Azure Key Vault secret ,并在值中删除插入符号 ^ 字符

azure - 创建2个publicIP并分配给nics

powershell - 从特定参数集中获取所有参数

powershell - powershell 中的新项目错误

powershell - 如何在powershell中使用findstr在整个驱动器中搜索字符串?

sql - 通过 Powershell 连接到 SQL Server(非本地)

powershell - 将 curl 转换为 PowerShell Invoke-WebRequest

powershell - 如何将字符串附加到 csv 文件的列

powershell - Powershell 中的 Runspace Dispose(特定于 GUI)