0

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??

Toto
  • 89,455
  • 62
  • 89
  • 125
  • 1
    Does this answer your question? [Removing spaces from a variable input using PowerShell 4.0](https://stackoverflow.com/questions/24355760/removing-spaces-from-a-variable-input-using-powershell-4-0) – zerocukor287 Jul 01 '21 at 12:28
  • no, the .replace(" ","") is removing spaces between words, not from start and end – aman kumar chagti Jul 01 '21 at 12:35
  • As an aside: [`Write-Host` is typically the wrong tool to use](http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful/), unless the intent is to write _to the display only_, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, or redirect it to a file. To output a value, use it _by itself_; e.g., `$value` instead of `Write-Host $value` (or use `Write-Output $value`, though that is rarely needed); see [this answer](https://stackoverflow.com/a/60534138/45375) – mklement0 Jul 01 '21 at 12:46
  • yeah, earlier i was using write-output to store output in file but for some reason, i need to get value on only prompt screen. so that's why, i used write-host. – aman kumar chagti Jul 02 '21 at 04:53

1 Answers1

7

This is because you're passing 3 distinct string arguments to Write-Host, the cmdlet then separates them with spaces:

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.


If the goal is to produce JSON, I'd suggest constructing a new object and letting ConvertTo-Json take care of the rest:

$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"
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206