Powershell -split 需要 return 一个数字而不是字符串

Powershell -split needs to return a number not string

我需要对字符串中的数量做一些乘法运算。我假设这是失败的,因为该值作为字符串而不是数字返回。这个 returns 的主体是数量的 1,但它在乘法上分崩离析。

720 * ([int]{
    $Inputstring ="Monthly Server Rental X 1 = .00"
    $CharArray =$InputString.Split(" ")
    $String1= $CharArray[4]; 
    write-host $String1
})

呃。

$Inputstring ="Monthly Server Rental X 2 = .00"; $CharArray =$InputString.Split(" "); [int]$String1= $CharArray[4]
$DUH = $String1 * 720

分裂可以清理一些吗?似乎 $String1 可以合并到拆分中。

简洁的PowerShell-idiomatic解决方案:

720 * (-split 'Monthly Server Rental X 2 = .00')[4]   # -> 1440

注:

    使用
  • A verbatim 字符串 ('...'),以防止将 </code> 解释为 PowerShell 变量,其名称是 <code>28

  • -split一元形式,PowerShell的string splitting operator运算符用于通过[=59=将字符串分割成token ] 空格,忽略前导和尾随空格。

  • 虽然 -split returns strings,但 LHS 是一个number(隐式类型 [int] (System.Int32)隐式 converts RHS 也为数字。

  • Abraham Zinala notes in the comments, Write-Host is typically the wrong tool to use, unless the intent is to write to the display only, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, redirect it to a file. To output a value, use it by itself; e.g., $value instead of Write-Host $value (or use Write-Output $value, though that is rarely needed). See also: the bottom section of .