Reputation: 518
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
Upvotes: 5
Views: 6615
Reputation: 10044
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
Upvotes: 11
Reputation: 518
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'
Upvotes: 0