Angshuman Agarwal
Angshuman Agarwal

Reputation: 4866

Post increment an integer in PowerShell initialised to a negative value

I have the following code which initialises a value to -1:

Set-Variable -Name ID -Value -1 -Scope local

When I do it like this,

$local:ID++

I get the following error:

The '++' operator works only on numbers. The operand is a 'System.String'.

I thought it will implicitly consider this as int. But, I have to use a workaround which is not neat:

Workaround:

$intVal = [int]$local:ID
$intval ++

Is there another approach?

Upvotes: 4

Views: 3332

Answers (1)

Shay Levy
Shay Levy

Reputation: 126842

$id is a string (type $id.gettype() to find its type). In order to initialize it as an integer, put it in parenthesis:

PS> Set-Variable -Name ID -Value (-1) -Scope local
PS> ($local:ID++) #increment and print the variable 
0

Upvotes: 3

Related Questions