Xeryn
Xeryn

Reputation: 11

Attempting to convert value into integer

I am very new to Powershell (I have only just poked around in the ISE a little bit for the last couple of days). I'm working on a program to pull battery capacity values from Windows systems and I am stuck in my code.

I want to perform arithmetic (specifically dividing the smaller value by the larger value) on the numerical values that are returned when I call "Remaining Capacity" and "Designed Capacity".

Thank you in advance for your time and energy given to my issue.

-Xeryn

<>

 CLS

 $a = Get-WmiObject -Namespace root\WMI -Class MSBatteryClass


 $a.RemainingCapacity
 $a.DesignedCapacity

 #Declaring variables
[Int]$r = $a.RemainingCapacity
[Int]$d = $a.DesignedCapacity


#Calling variables
$r
$d


#Calculate capacity percentage
$r / $d

When I run $r, ISE outputs: PS C:\WINDOWS\system32> $r 42340

When I run $d, ISE outputs: PS C:\WINDOWS\system32> $d 45800

When I run $r / $d, ISE outputs: Method invocation failed because [System.Object[]] does not contain a method named 'op_Division'. At line:1 char:1

Upvotes: 0

Views: 86

Answers (1)

Doron Kedem-Goldman
Doron Kedem-Goldman

Reputation: 158

$a.<param> is of type Object[], which typically could not be directly converted to type Int in PowerShell. Use $var.GetType() to determine the type of a variable.

An easy solution is to begin with casting the variable to String, and casting it to Int afterwards, like so:

Option A:

[Int][String]$r = $a.RemainingCapacity
[Int][String]$d = $a.DesignedCapacity

Option B:

[Int]$r = $a.RemainingCapacity -as [String]
[Int]$d = $a.DesignedCapacity -as [String]

The -as operator tries to convert the input object to the specified .NET type. If it succeeds, it returns the converted object. If it fails, it returns $null. It does not return an error. See docs.

NOTE: In order for that to work, the value of $a.<param> must be in the correct Int32 format.

Upvotes: 1

Related Questions