powershell - 将 Cmdlet 输出与字符串连接起来

标签 powershell concatenation

如何将命令的输出与文本字符串在一行上的组合输出到主机?

我正在尝试结合:(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 当您使用 + 时,它会尝试将第二个参数转换为第一个参数的类型。 EncryptionPercentageSingle 因此它会尝试将 '% 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/

相关文章:

sql - 如何在 SQL Server 2005 中将多行组合成逗号分隔的列表?

javascript - 如何在同一字符串中console.log对象定义和文本?

c# - 在 C# cmdlet 中创建 PowerShell PSObject

xml - 通过 Powershell 替换 xml 文件中的文本

powershell - WinRM 无法完成操作。验证指定的计算机名称是否有效

powershell - 替换管道中的文字

windows - win32_physicalMemory.Capacity 在 powershell 中返回 null

C 编程 : ls function sort by file, 可执行文件和目录

ansible - 在ansible playbook中连接多个变量和字符串

c# - 为什么我不能在公共(public)静态字符串上使用串联