如何在一行中输出命令输出和文字字符串的组合?
我正在尝试将(Get-BitLockerVolume -MountPoint X:).EncryptionPercentage
(返回12
)与文字'% complete'
合并,如下所示:
(Get-BitLockerVolume -MountPoint X:).EncryptionPercentage + '% complete'
作为回报,我希望得到:
完成12%
相反,我得到错误无法将值“%complete”转换为“System.Single”。错误:“输入字符串的格式不正确。”
如何在一条线上完成此操作?我已经搜索了一个解决方案,但显然不知道如何表达这个问题,因为我不断获得有关如何连接字符串或变量但不是命令输出的信息。示例:PowerShell: concatenate strings with variables after cmdlet
答案 0 :(得分:6)
使用PowerShell时,如果使用+
,它会尝试将第二个参数转换为第一个参数的类型。 EncryptionPercentage
是Single
,因此它会尝试将'% complete'
投射到导致错误的Single
。
要解决此问题,您可以预先将EncryptionPercentage
强制转换为字符串。
[string](Get-BitLockerVolume -MountPoint X:).EncryptionPercentage + '% complete'
或者你可以使用子表达式$()
"$((Get-BitLockerVolume -MountPoint X:).EncryptionPercentage)% complete"
正如TessellatingHeckler指出的那样,.ToString()
方法也将转换为字符串
(Get-BitLockerVolume -MountPoint X:).EncryptionPercentage.ToString() + '% complete'
您可以使用格式运算符-f
将值插入字符串。其中{}
是-f
'{0} % Complete' -f (Get-BitLockerVolume -MountPoint X:).EncryptionPercentage
答案 1 :(得分:0)
正如错误消息中暗示的那样,PowerShell正在尝试将(强制转换)'% complete'
转换为System.Single类型。那是因为你的命令输出是一个数字。
要获得您要求的输出,请在命令之前使用[string]
将数字输出转换为字符串。然后命令的两个元素将被视为字符串:
[string](Get-BitLockerVolume -MountPoint X:).EncryptionPercentage + '% complete'