如何将命令的输出与文本字符串在一行上的组合输出到主机?
我正在尝试结合:(Get-BitLockerVolume -MountPoint X:).EncryptionPercentage
(返回 12
)与文字 '% complete'
如下:
(Get-BitLockerVolume -MountPoint X:).EncryptionPercentage + '% complete'
作为返回,我希望得到:
12% complete
相反,我收到错误无法将值“% complete”转换为类型“System.Single”。错误:“输入字符串的格式不正确。”
我怎样才能在一行中做到这一点?我已经搜索了一个解决方案,但显然不知道如何表达这个问题,因为我一直在获取有关如何连接字符串或变量的信息,但不是命令输出。示例:PowerShell: concatenate strings with variables after cmdlet
最佳答案
使用 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
关于powershell - 将 Cmdlet 输出与字符串连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45019847/