1

I need to do some multiplication on the quantity in the string. I'm assuming that this is failing because the value is being returned as a string and not a number. The main body of this returns a 1 for the quantity but it falls apart on the multiplication.

720 * ([int]{
    $Inputstring ="Monthly Server Rental X 1 = $28.00"
    $CharArray =$InputString.Split(" ")
    $String1= $CharArray[4]; 
    write-host $String1
})
zett42
  • 25,437
  • 3
  • 35
  • 72
4evernoob
  • 135
  • 8
  • 3
    you're not returning anything. `Write-Host` writes to the host. `$string1` alone suffices, or use `Write-Output`, and it also doesn't need to be in a scriptblock `{..}`. This should be enough `[int](...)`. The type `[int]` defaults to `[int32]` as well, just as an fyi. – Abraham Zinala May 31 '22 at 20:33

2 Answers2

2

A concise, PowerShell-idiomatic solution:

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

Note:

  • A verbatim string ('...') is used, so as to prevent interpretation of $28 as a PowerShell variable whose name is 28

  • The unary form of -split, PowerShell's string splitting operator operator is used to split the string into tokens by non-empty runs of whitespace, ignoring leading and trailing whitespace.

  • While -split returns strings, the fact that the LHS is a number (implicitly of type [int] (System.Int32) implicitly converts the RHS to a number too.

  • As 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 this answer.

mklement0
  • 382,024
  • 64
  • 607
  • 775
0

DUH.

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

Could the split be cleaned up some? Seems like the $String1 could be incorporated in the split.

4evernoob
  • 135
  • 8