Powershell: appending a percent sign to the end of a variable
Solution 1
Explanation:
Adding " "
around your output to treat it as a string and then append the variable onto the end. This means you are able to switch it over from %
to a string such as Percent Remaining
.
Hope this helps, you were close!
Code:
$disk = Get-WmiObject -ComputerName $Computer -Class Win32_LogicalDisk -Filter "Caption = 'D:'"
If (!($disk)) {
$DiskpercentFree = "n/a"
}
Else {
$deviceID = $disk.DeviceID
[float]$size = $disk.Size;
[float]$freespace = $disk.FreeSpace;
$diskpercentFree1 = [Math]::Round(($freespace / $size) * 100)
$Percent = '%'
$diskpercentFree = "$diskpercentFree1" + $Percent
}
Example Result of $diskpercentFree
:
PS C:\Windows\system32> $DiskpercentFree
57%
Solution 2
There are a few ways to do this:
Assign variable as string:
$diskpercentFree = "$diskpercentFree1$Percent"
Cast the double value as a string:
$diskpercentFree = "$diskpercentFree1" + $Percent
# Or
$diskpercentFree = [string]$diskpercentFree1 + $Percent
And no need to use a separate variable for the %
character:
$diskpercentFree = "$diskpercentFree1%"
Related videos on Youtube
TOGEEK
Updated on June 04, 2022Comments
-
TOGEEK almost 2 years
I am trying to add the percent sign ("%") to append to a variable:
$disk = Get-WmiObject -ComputerName $Computer -Class Win32_LogicalDisk -Filter "Caption = 'D:'" If (!($disk)) { $DiskpercentFree = "n/a" } Else { $deviceID = $disk.DeviceID [float]$size = $disk.Size; [float]$freespace = $disk.FreeSpace; $diskpercentFree1 = [Math]::Round(($freespace / $size) * 100) $Percent = "%" $diskpercentFree = $diskpercentFree1 + $Percent }
But all I get is:
Cannot convert value "%" to type "System.Double". Error: "Input string was not in a correct format."
Presumably because it thinks that the "+" operator is making a calculation? I've tried various concat options but can't seem to get it right. Can anyone help?
-
TOGEEK over 6 yearsI chose $diskpercentFree = [String]$diskpercentFree1+"$Percent". I did actually try to convert the variable: "[String]$diskpercentFree". Thanks very much!
-
arco444 over 6 years@JDGEEK then technically you should accept the other answer as that was the one that listed that method