4evernoob
4evernoob

Reputation: 115

Powershell -split needs to return a number not string

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
})

Upvotes: 1

Views: 98

Answers (2)

mklement0
mklement0

Reputation: 438198

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.

Upvotes: 2

4evernoob
4evernoob

Reputation: 115

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.

Upvotes: 0

Related Questions