Search code examples
powershellstring-concatenation

Powershell: appending a percent sign to the end of a variable


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?


Solution

  • 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%