简体   繁体   English

如何删除Powershell中的前导和尾随空格?

[英]How to remove leading and trailing spaces in Powershell?

Where I run the following command:我在哪里运行以下命令:

Write-Host '"os":"'(Get-CimInstance -ClassName CIM_OperatingSystem).Caption'",'

I get the following output:我得到以下输出:

"os":" Microsoft Windows 10 Pro ",

How to remove the leading and trailing space in the output??如何删除输出中的前导和尾随空格?

This is because you're passing 3 distinct string arguments to Write-Host , the cmdlet then separates them with spaces:这是因为您将 3 个不同的字符串参数传递给Write-Host ,然后 cmdlet 将它们用空格分隔:

Write-Host '"os":"'(Get-CimInstance -ClassName CIM_OperatingSystem).Caption'",'
           \______/\______________________________________________________/\__/

Change to改成

Write-Host """os"":""$((Get-CimInstance -ClassName CIM_OperatingSystem).Caption)"","

Here, we create 1 (one!) string with correctly escaped quotation marks, and Write-Host won't attempt to add any whitespace.在这里,我们使用正确转义的引号创建 1(一个!)字符串,并且Write-Host不会尝试添加任何空格。


If the goal is to produce JSON, I'd suggest constructing a new object and letting ConvertTo-Json take care of the rest:如果目标是生成 JSON,我建议构建一个新对象并让ConvertTo-Json处理其余的事情:

$data = [pscustomobject]@{
  os = (Get-CimInstance -ClassName CIM_OperatingSystem).Caption
}

$data |ConvertTo-Json

The output of which will be something like:其输出将类似于:

{
    "os":  "Microsoft Windows 10 Enterprise"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM