5

How do I output to the host the combination of the output of a command and a literal string on a single line?

I'm trying to combine: (Get-BitLockerVolume -MountPoint X:).EncryptionPercentage (which returns 12) with the literal '% complete' as follows:

(Get-BitLockerVolume -MountPoint X:).EncryptionPercentage + '% complete'

In return I expect to get:

12% complete

Instead I get the error Cannot convert value "% complete" to type "System.Single". Error: "Input string was not in a correct format."

How can I do this on a single line? I've searched for a solution but apparently don't know how to phrase this question because I keep getting information on how to concatenate strings or variables, but not command output. Examples: PowerShell: concatenate strings with variables after cmdlet

1
  • 3
    (Get-BitLockerVolume -MountPoint X:).EncryptionPercentage.ToString() + '% complete' or '{0} % Complete' -f (Get-BitLockerVolume -MountPoint X:).EncryptionPercentage Commented Jul 10, 2017 at 19:13

2 Answers 2

11

With PowerShell when you use + it will try to cast the second argument to the type of the first. EncryptionPercentage is a Single so it will try to cast '% complete' to an Single which throws an error.

To get around this, you can either cast EncryptionPercentage to string preemptively.

 [string](Get-BitLockerVolume -MountPoint X:).EncryptionPercentage + '% complete'

Or you can do string interpolation inside double quotes, using a subexpression $()

"$((Get-BitLockerVolume -MountPoint X:).EncryptionPercentage)% complete"

As TessellatingHeckler points out, the .ToString() method will also convert to a String

(Get-BitLockerVolume -MountPoint X:).EncryptionPercentage.ToString() + '% complete'

And you can use the format operator -f to insert values into a string. Where {} is the index of the comma separated arguments after -f

'{0} % Complete' -f (Get-BitLockerVolume -MountPoint X:).EncryptionPercentage
Sign up to request clarification or add additional context in comments.

Comments

0

As hinted in the error message, PowerShell is trying to convert (cast) '% complete' to the type System.Single. That's because the output of your command is a number.

To get the output you're asking for, use [string] before the command to cast the number output into a string. Then both elements of the command will be treated as a string:

[string](Get-BitLockerVolume -MountPoint X:).EncryptionPercentage + '% complete'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.