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
Best Answer
+
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:Other possible notations:
The result is always the same.
Alternatively, you can use string formatting:
will just use the value as it is. If you want a more uniform output you can specify how the value should be handled:
will always output two decimal values, even for round numbers.
Here is a nice summary of the formatting options.