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:
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"
}
Write-Host should never be used to output data.
Write-Hostis typically the wrong tool to use, 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.,$valueinstead ofWrite-Host $value(or useWrite-Output $value, though that is rarely needed); see this answer