1

I am doing a script that calculates the % free space on our hosts.

$percent = [math]::Round($AvailableMemory * 100 / $TotalMemory)

It gives me the correct number, but when I want to print the $percent variable with the value + '%' it do not let me.

How can I print the value with this simbol? For example 33%, 55% ...

Best regards

  • 1
    Define "does not let me". What are your trying and what is the actual error message you get? – Gerald Schneider Jan 16 '19 at 9:18
  • For example I tried: $test = $percent+'%' also $test = $percent '%'. And the error is: Cannot convert value "%" to type "System.Double". Error: "Input string was not in a correct format." – Simpleacc Jan 16 '19 at 9:20
  • Try "{0:p}" -f $percent, you have to change your calculation, though. social.technet.microsoft.com/wiki/contents/articles/… – Lenniey Jan 16 '19 at 9:22
  • Thank you Lenniey! I just needed to add a "/100" in the $percent form and the {0:p} worked fine. Thanks – Simpleacc Jan 16 '19 at 9:28
4

+ is used to concatenate strings, but it is also used to do math operations. Since the result of your calculation is a float, powershell tries to convert your % into a float as well, so it can add it to the calculated value.

You can append the % sign by converting your float into a string first:

$percent.toString() + '%'

Other possible notations:

"$percent" + "%"
"$percent%"

The result is always the same.

Alternatively, you can use string formatting:

"{0}%" -f $percent

will just use the value as it is. If you want a more uniform output you can specify how the value should be handled:

"{0:N2}%" -f $percent

will always output two decimal values, even for round numbers.

Here is a nice summary of the formatting options.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.