【问题标题】:Convert string to int for subtraction将字符串转换为 int 以进行减法
【发布时间】:2014-06-11 13:21:59
【问题描述】:

这是我的代码,

$fourCount = 0
$rowCount = 0
foreach($row in $ResultsTable){
  if ($row.'RowType' -eq 6) {
    if ($fourCount -gt 0) {
      #Sort-Object {$row.'CheckDate'} - descending
      $remainAmount = $currentAmount - $checkAmount
      $ResultsTable.Rows[$rowCount - 1].'Final' = $remainAmount
      $currentAmount = @()
      $fourCount = 0
      $remainAmount = 0
    }
    $checkAmount = [int]$row.'amount'
    $rowCount = $rowCount + 1
  } elseif ($row.'RowType' -eq 4) {
    if($row.'current'.Length -eq $NULL) {
      Continue
    } else {
      $currentAmount += [int]$row.'current'
      $rowCount = $rowCount + 1
      $fourCount++
    } 
  } else {
    Continue
  }
}

我在运行代码时遇到的问题是

方法调用失败,因为 [System.Object[]] 不包含 名为“op_Subtraction”的方法。

$remainAmount = $currentAmount - FullyQualifiedErrorId : MethodNotFound

根据我的阅读,我将所有内容都转换为 int,但它仍然无法运行。谁能告诉我为什么?

【问题讨论】:

    标签: string powershell int


    【解决方案1】:

    在第 9 行,您将 $currentAmount 初始化为一个空数组:

    $currentAmount = @()
    

    然后您将 [int] 项累积到该数组中:

    $currentAmount += [int]$row.'current'
    

    所以你拥有的是一个 [int] 数组。

    最终你尝试对该数组进行减法运算:

    $remainAmount = $currentAmount - $checkAmount
    

    它失败了。

    错误消息中的 [Type[]] 语法表明它是一个数组,您不能对其进行减法运算。

    【讨论】:

    • 我明白了....这解决了我的问题。只需将 [0] 添加到它运行的末尾。再次感谢!
    猜你喜欢
    • 2011-08-24
    • 1970-01-01
    • 2018-05-10
    • 2011-10-02
    • 2011-03-06
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    相关资源
    最近更新 更多