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