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
- $r / $d
-
+ CategoryInfo : InvalidOperation: (op_Division:String) [], Runti meException + FullyQualifiedErrorId : MethodNotFound
$a.<param>is of typeObject[], which typically could not be directly converted to typeIntin 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 toIntafterwards, like so:Option A:
Option B:
NOTE: In order for that to work, the value of
$a.<param>must be in the correctInt32format.