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

4
  • 1
    Does this answer your question? Removing spaces from a variable input using PowerShell 4.0 Commented Jul 1, 2021 at 12:28
  • no, the .replace(" ","") is removing spaces between words, not from start and end Commented Jul 1, 2021 at 12:35
  • As an aside: Write-Host is 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., $value instead of Write-Host $value (or use Write-Output $value, though that is rarely needed); see this answer Commented Jul 1, 2021 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. Commented Jul 2, 2021 at 4:53

1 Answer 1

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"
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nicely done; also worth mentioning that Write-Host should never be used to output data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.