Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell How to add a number into a variable

Tags:

powershell

how can I add a number to another number contained into a variable?

$t0 = Get-date -UFormat "%H%M"
$t1 = $t0 + 10

so, if $t0 is 1030, I would $t1 values 1040.

like image 241
rschirin Avatar asked Dec 11 '22 16:12

rschirin


2 Answers

force to [int] before assign value to $t0 ( get-date -uformat returns [string] type ):

[int]$t0 = Get-date -UFormat "%H%M"
$t1 = $t0 + 10

if you change the order the coercing feature of powershell gives the expected value:

$t0 = Get-date -UFormat "%H%M"
$t1 = 10 + $t0

because second operand is cast to type of first one

like image 167
CB. Avatar answered Dec 14 '22 22:12

CB.


After doing $t0 = Get-date -UFormat "%H%M", $t0 does not contain a number, but a String. You can verify this by calling $t0 | Get-Member.

One easy way to get around this is to cast it to int: [int]$t0 + 10, which will do normal integer addition.

like image 42
Alex Avatar answered Dec 15 '22 00:12

Alex